我有一个服务器块,如下所示:
server { listen 80; # ... location / { try_files $uri $uri/ /index.php?$query_string; # I've tried adding "$uri.php" like so, but it downloads the php file instead. # try_files $uri $uri/ $uri.php /index.php?$query_string; } location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php/php7.1-fpm.sock; fastcgi_index index.php; include fastcgi_params; } }
如果这样的请求来自http://example.com/random/page ,我需要Nginx将其重写到http://example.com/random/page.php而无需更改用户的url。 它还需要将该请求传递给其他位置块。 如果该文件不存在,它应该返回一个404。我怎样才能做到这一点?
其中一种可能性:
server { listen 80; ... location / { try_files $uri $uri/ @rewrite; } location @rewrite { rewrite ^ $uri.php last; } location ~ \.php$ { try_files $uri =404; fastcgi_pass unix:/var/run/php/php7.1-fpm.sock; include fastcgi_params; } }
无论如何,您应该在location ~ \.php$块中testing文件是否存在,如本应用笔记所述 。