这是我的 nginx 配置:
server {
# Running port
listen 80;
error_page 404 /404;
# Settings to by-pass for static files
location ^~ / {
# Example:
# root /full/path/to/application/static/file/dir;
root /var/www;
include /etc/nginx/mime.types;
try_files $uri $uri/ @htmlext;
}
location ~ \.html$ {
try_files $uri = 404;
}
location @htmlext {
rewrite ^(.*)$ $1.html last;
}
}
目的是/404
在发生 404 错误时显示该页面。但是,500 Internal Server Error
当我访问不存在的页面时,我得到了一个错误。为什么?
答案1
我认为你的主要问题是在这里:rewrite ^(.*)$ $1.html last;
以及标志的使用last
。
这是医生怎么说:
如果这些指令 [rewrite] 放在 location 内,则
last
标志应该替换为break
,否则 nginx 将进行 10 次循环并返回 500 错误
这是我们在日志中可以看到的内容。这里我询问了fake.html
不存在的内容:
[debug] 3480#0: *1 http script var: "/fake.html.html.html.html.html.html"
[debug] 3480#0: *1 trying to use file: "/fake.html.html.html.html.html.html" "/var/www/fake.html.html.html.html.html.html"
[debug] 3480#0: *1 http script var: "/fake.html.html.html.html.html.html"
[debug] 3480#0: *1 trying to use dir: "/fake.html.html.html.html.html.html" "/var/www/fake.html.html.html.html.html.html"
[debug] 3480#0: *1 trying to use file: "@htmlext" "/var/www@htmlext"
[error] 3480#0: *1 rewrite or internal redirection cycle while redirect to named location "@htmlext"....
[debug] 3480#0: *1 http finalize request: 500, "/fake.html.html.html.html.html.html?" a:1, c:7
[debug] 3480#0: *1 http special response: 500, "/fake.html.html.html.html.html.html?"
有趣的 ! ;)
因此,用以下方式替换重写规则:rewrite ^(.*)$ $1.html break;
404
或者,如果指令中不存在任何文件,则可以返回try_files
:
try_files $uri $uri/ @htmlext =404;
然而,此时,您的自定义404
页面不应该起作用。
以下是我的建议:
server {
# Running port
listen 80;
error_page 404 /404.html;
location ~^/404.html {
root /var/www;
internal;
}
# Your other stuff Here ......
}
答案2
尝试替换这个:
try_files $uri = 404;
和:
try_files $uri =404;
答案3
正确定义404页面的方法:
error_page 404 /404.html;
location /404.html {
internal;
}