Nginx和处理文件没有扩展

我试图让Nginx处理没有扩展名的PHP文件(即处理http:// localhost / sample与处理http://localhost/sample.php的方式相同)。

这是我的网站configuration:

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工作正常)。

打开debugging时,我在日志中看到以下内容:

 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的位置)。

我错过了什么? :) 谢谢!

  try_files $uri $uri/ $uri.html @extensionless =404; 

是的, @extensionless被视为一个正常的文件,这是因为你已经在try_files@extensionless之后添加了一个额外的=404 @extensionless部分只会作为内部重定向到另一个上下文的最后一个参数。

如果您不仅希望支持不带.php处理请求,而且还希望从任何请求中.php ,则可能需要执行以下操作:

 location / { if (-e $request_filename.php){ rewrite ^/(.*)$ /$1.php; } } location ~ \.php$ { if ($request_uri ~ ^/([^?]*)\.php(\?.*)?$) { return 302 /$1$2; } fastcgi_... } 

只是更新(如果有人认为这有用),我最终得到它的工作。

这是诀窍的配置:

 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; } } 

用最快最简单的方法避免使用缓慢的重写和邪恶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; }