[英]Redirect /file-name to file-name.php in Nginx
我的結構項目
- index.php
- abc.php
- folder/
---- def.php
我的 nginx.conf
server {
listen 80 default_server;
root /var/www/public;
index index.html index.htm index.php;
server_name _;
location / {
try_files $uri $uri/ /index.php$is_args$args;
}
location /index.php {
include snippets/fastcgi-php.conf;
fastcgi_param SCRIPT_FILENAME $request_filename;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
}
如何更改 nginx.conf 以使用domain/abc
作為 href 而不是domain/abc.php
謝謝!
這通常被稱為“無擴展 PHP”,有很多解決方案,這只是其中的一種:
location / {
try_files $uri $uri/ @php;
}
location @php {
try_files $uri.php $uri/index.php /index.php =404;
include snippets/fastcgi-php.conf;
fastcgi_param SCRIPT_FILENAME $request_filename;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
如果您希望以.php
結尾的 URI 也能正常工作,請添加:
location ~* ^(.*)\.php$ { return 301 $1$is_args$args; }
高性能解決方案是簡單地指定所需位置,並將 map 指定到相應的 PHP 腳本。
location = /abc {
include snippets/fastcgi-php.conf;
fastcgi_param SCRIPT_FILENAME $document_root/abc.php;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}
這將確保/abc
由腳本/abc.php
處理。
如果您還想“隱藏”對/abc.php
的訪問,您可以添加:
location = /abc.php {
return 404;
}
為什么這樣很快,是因為精確匹配(帶等號)不涉及前綴匹配和正則表達式處理。
此外,我們不需要使用try_files
(它有性能問題)。 具體來說,如果使用@RichardSmith 的答案中的配置,它可能會對任意請求產生多達 5 次不必要的文件存在性檢查,並對每個請求產生 3 次文件存在性檢查/abc
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.