Iptables使用php-fpm对nginx进行规则

I am setting up iptables rules on the server where nginx and php-fpm are running. I have allow both 80 and 443 ports but as I see there are also addiitonal connections to higher ports that are blocked.

Sample output of

netstat -anpn | grep -v ":80"

tcp        0      1 10.0.0.1:8109       10.1.2.24:29837     SYN_SENT    19834/nginx: worker
tcp        0      1 10.2.3.45:31890     10.0.0.1:26701      SYN_SENT    17831/nginx: worker

10.0.0.1 is server IP, others are clients.

My iptables rules:

iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT

Can someone explain:

  1. Why do nginx uses ports different from standard 80 and 443.

  2. What is this additional ports range?

  3. How to properly allow connections to nginx with iptables?

Thanks in advance!

I use PHP-FPM with Nginx as well. I block all ports except 22/80/443 in iptables and haven't experienced any issues with connectivity. I examined my own netstat and it looks identical to your output. Are you sure your iptables rules are correct? Could you post the output of sudo iptables -L

Nginx will typically perform internal redirects when processing a request and this will establish connections on high numbered ports. I do not believe you can find this range.

Here is what I see for example:

tcp        0      0 192.168.0.126:80        0.0.0.0:*               LISTEN      9432/nginx: worker
tcp        0      0 192.168.0.126:80        192.168.0.177:62950     ESTABLISHED 9432/nginx: worker
tcp        0      0 192.168.0.126:80        192.168.0.177:62949     ESTABLISHED 9432/nginx: worker
tcp        0      0 192.168.0.126:80        192.168.0.177:62947     ESTABLISHED 9432/nginx: worker
unix  3      [ ]         STREAM     CONNECTED     29213    9432/nginx: worker 

The reason your firewall rules work is because you:

  1. Have opened the required ports that your Nginx server listeners need (i.e. 80 and 443)

  2. You have included the following firewall rule that allows all requests to localhost (127.0.0.1) so Nginx internal redirects that open high numbered ports are not blocked:

    iptables -A INPUT -i lo -j ACCEPT

So to answer your questions:

  1. Nginx server listeners can listen to any port you like not just 80 and 443. Why it uses additional ports is for internal redirects and as such an aspect of the implementation.

  2. I do not believe you can find this range. In fact I would doubt any code would ask the system to utilize a certain port but rather would ask the OS for a high numbered unused port.

  3. You may not have realized it but the firewall rules you implemented should work fine.