如果没有尾部斜杠,Nginx会导致301重定向 [英] Nginx causes 301 redirect if there's no trailing slash
问题描述
我正在使用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 tohttp://localhost/test/
. This is not what I want.
根据我搜索过的内容,我尝试了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 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
块:
index index.html index.htm;
并修改try_files
看起来像这样:
try_files $uri $uri/ =404;
它也应该工作.
这篇关于如果没有尾部斜杠,Nginx会导致301重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!