如果没有尾部斜杠,Nginx 会导致 301 重定向 [英] Nginx causes 301 redirect if there's no trailing slash

查看:117
本文介绍了如果没有尾部斜杠,Nginx 会导致 301 重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 NAT 的虚拟机中运行 nginx,当我从主机访问它时遇到重定向问题.

I'm running nginx in a Virtual Machine using NAT and I'm having redirection issues when I access it from the host machine.

  • http://localhost:8080/test/index.htm:有效.
  • http://localhost:8080/test/:有效.
  • http://localhost:8080/test/index.htm: works.
  • http://localhost:8080/test/: works.
  • http://localhost:8080/test:重定向到 http://localhost/test/ .这不是我想要的.(注意它去掉了端口号)
  • http://localhost:8080/test: redirects to http://localhost/test/ . This is not what I want. (notice it strips the port number)

根据我搜索的内容,我尝试了 server_name_in_redirect off;rewrite ^([^.]*[^/])$ $1/Permanent;,都没有成功.

Based on what I've googled, I tried server_name_in_redirect off; and rewrite ^([^.]*[^/])$ $1/ permanent;, both with no success.

server {
    listen       80;
    server_name  localhost;
    # server_name_in_redirect off;
    
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm index.php;
    }

    location ~ .php$ {
    # rewrite ^([^.]*[^/])$ $1/ permanent;
        root           /usr/share/nginx/html;
        try_files      $uri =404;
        #fastcgi_pass   127.0.0.1:9000;
        fastcgi_pass   unix:/tmp/php5-fpm.sock;
        fastcgi_index  index.php;
        include        fastcgi_params;
    }


    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

}

推荐答案

我在 serverfault;为方便起见,转载于此:

I posted a possible solution to this problem on serverfault; reproduced here for convenience:

如果我正确理解问题,您希望自动提供服务,而不使用 301 重定向,http://example.com/foo/index.html 当请求是针对 http://example.com/foo 没有斜线?

If I understand the question correctly, you want to automatically serve, without using a 301 redirect, http://example.com/foo/index.html when the request is for http://example.com/foo with no trailing slash?

如果是这样,我发现这个 try_files 配置可以工作:

If so I've found this try_files configuration to work:

try_files $uri $uri/index.html $uri/ =404;

  • 第一个 $uri 与 uri 完全匹配
  • 第二个 $uri/index.html 匹配包含 index.html 的目录,其中路径的最后一个元素匹配目录名称,不带斜线
  • 第三个 $uri/ 匹配目录
  • 如果前面的模式都不匹配,第四个 =404 将返回 404 错误页面.
    • The first $uri matches the uri exactly
    • The second $uri/index.html matches a directory containing the index.html where the last element of the path matches the directory name, with no trailing slash
    • The third $uri/ matches the directory
    • The fourth =404 returns the 404 error page if none of the preceding patterns match.
    • 取自服务器故障答案

      如果您在 server 块中添加:

      If you add in the server block:

      index index.html index.htm;
      

      并修改 try_files 如下所示:

      try_files $uri $uri/ =404;
      

      它也应该有效.

      这篇关于如果没有尾部斜杠,Nginx 会导致 301 重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆