我正在尝试让Nginx处理没有扩展名的php文件(即以处理http://localhost/sample的方式处理http://localhost/sample.php)。
这是我的网站配置:
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
server_name localhost;
root /var/www;
index index.html index.php;
location ~ \.(hh|php)$ {
fastcgi_keep_conn on;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location / {
try_files $uri $uri/ $uri.html @extensionless =404;
}
location @extensionless {
rewrite ^(.*)$ $1.php last;
}
}
据我所知,应该这样做。但是 - 它没有。尝试http://localhost/sample只会让我进入404页面(而http://localhost/sample.php可以正常工作)。
打开调试时,我在日志中看到以下内容:
2015/07/19 15:37:00 [debug] 4783#0: *1 http script var: "/sample"
2015/07/19 15:37:00 [debug] 4783#0: *1 trying to use file: "/sample" "/var/www/sample"
2015/07/19 15:37:00 [debug] 4783#0: *1 http script var: "/sample"
2015/07/19 15:37:00 [debug] 4783#0: *1 trying to use dir: "/sample" "/var/www/sample"
2015/07/19 15:37:00 [debug] 4783#0: *1 http script var: "/sample"
2015/07/19 15:37:00 [debug] 4783#0: *1 http script copy: ".html"
2015/07/19 15:37:00 [debug] 4783#0: *1 trying to use file: "/sample.html" "/var/www/sample.html"
2015/07/19 15:37:00 [debug] 4783#0: *1 trying to use file: "@extensionless" "/var/www@extensionless"
2015/07/19 15:37:00 [debug] 4783#0: *1 trying to use file: "=404" "/var/www=404"
这很奇怪。它基本上看起来像@extensionless被视为纯文件名(而不是导致重写URL的位置)。
我错过了什么? :) 谢谢!
答案 0 :(得分:7)
最终,只是更新(如果有人发现这个有用)我就让它工作了。
这是完成诀窍的配置:
server {
listen 80;
root /var/www;
index index.html index.htm index.php;
server_name localhost;
location / {
if (!-e $request_filename){
rewrite ^(.*)$ /$1.php;
}
try_files $uri $uri/ =404;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
答案 1 :(得分:5)
try_files $uri $uri/ $uri.html @extensionless =404;
是的,@extensionless
被视为普通文件,那是因为您在try_files
=404
之后添加了额外的@extensionless
- {{1} part只能作为最后一个参数作为内部重定向到另一个上下文。
如果您不仅要支持处理不@extensionless
的请求,而且还要从任何请求中删除.php
,您可能需要执行以下操作:
.php
答案 2 :(得分:3)
最好以最快最简单的方式避免使用慢速重写和邪恶的IF:
location ~ ^(.*)\.php$ # If PHP extension then 301 redirect to semantic URL
{
return 301 $scheme://$server_name$1$is_args$args;
}
location ~ ^/(.*)
{
try_files $uri.php @static; # If static, serve it in @static
include fastcgi_params; # if semantic, serve it here
fastcgi_param SCRIPT_FILENAME $document_root/$1.php;
}
location @static
{
try_files $uri =404;
}