防止NGINX移除端口

Gur*_*erz 12 port nginx strip url-rewriting

我想在重写时动态保持服务器名称和端口:假设防火墙将端口 8081 重定向到 80。因此,如果我使用“192.168.1.123/frontend”或“my.domain.tld:8081/”等访问网络服务器前端”我应该重定向到“192.168.1.123/frontend/”或“my.domain.tld:8081/frontend/”

如果我使用普通redirect rewrite ^(.*[^/])$ $1/ permanent;端口并使用端口 8081 访问,则端口被删除。(我已经试过了port_in_redirect off;

我几乎使用默认配置:

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/html;
        index index.php index.html index.htm index.nginx-debian.html;

        server_name _;
        rewrite ^(.*[^/])$ $1/ permanent;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        location ~ \.php$ {
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                include fastcgi.conf;
        }
}
Run Code Online (Sandbox Code Playgroud)

谢谢期待!


解决方案: 感谢 NGINX 邮件列表!我用重写规则解决了这个问题:

if (-d $request_filename) {
    rewrite [^/]$ $scheme://$http_host$uri/ permanent;
}
Run Code Online (Sandbox Code Playgroud)

Ghi*_*his 9

我终于找到了解决您所描述问题的方法。我让它与 URL 重写一起工作,但这似乎有点矫枉过正。

因此,对于任何有同样问题的人来说,最干净的解决方案似乎是替换它:

proxy_set_header Host $host;
Run Code Online (Sandbox Code Playgroud)

有了这个 :

proxy_set_header Host $http_host;
Run Code Online (Sandbox Code Playgroud)

通过此设置,Nginx 将在您的重定向中保留端口,无论您的防火墙配置如何。

希望这可以帮助。干杯!