如何从nginx中的URL中删除文件扩展名?
问题描述:
比方说,我有一个名为careers.php
文件,我怎么为这个文件,当他们点击进入http://example.com/careers
没有两个.html
和.php
文件与nginx的文件扩展名的链接?如何从nginx中的URL中删除文件扩展名?
请注意,该解决方案必须考虑查询字符串。例如,URL可能是
http://example.com/careers?lang=fr
。此外,我想解决方案也尝试子目录以及。例如;如果服务器上的我的文件夹结构是
/views/careers.php
,我想http://example.com/careers
仍然服务于/views/careers.php
。
我现在的配置如下所示:
server {
listen 80 default_server;
root /usr/share/nginx/landing-page;
index index.php index.html;
server_name example.com;
location/{
try_files $uri $uri/ =404;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
答
一个共同的解决方案使用try_files
与命名的位置。现有的location ~ \.php$
块用于处理.php
文件。还要避免任何if
陈述。
location/{
try_files $uri $uri/ @rewrite;
}
location @rewrite {
rewrite^$uri.php last;
}
location ~ \.php$ {
try_files $uri =404;
...
}
答
您可以使用try_files
:
try_files $uri $uri.php $uri/ =404;
'try_files $ uril $ uri.php /views/$uri.php $ uri/= 404;'为我的第二点工作?此外,这将允许查询字符串? –
@EdwardMaxedon是的,查询字符串将不受影响。对于第二点,考虑到'$ uri'将包含前导斜杠 – Vasfed
我现在已经注意到,而不是将文件作为.php文件处理,它在我访问该页面时下载。 'location〜\ .php $'块是否需要更新? –