Php
如何使 Nginx 將對不存在的文件的所有請求重定向到單個 php 文件?
我有以下 nginx 虛擬主機配置:
server { listen 80 default_server; access_log /path/to/site/dir/logs/access.log; error_log /path/to/site/dir/logs/error.log; root /path/to/site/dir/webroot; index index.php index.html; try_files $uri /index.php; location ~ \.php$ { if (!-f $request_filename) { return 404; } fastcgi_pass localhost:9000; fastcgi_param SCRIPT_FILENAME /path/to/site/dir/webroot$fastcgi_script_name; include /path/to/nginx/conf/fastcgi_params; } }
我想將所有與存在的文件不匹配的請求重定向到 index.php。這適用於目前大多數 URI,例如:
example.com/asd example.com/asd/123/1.txt
既不存在
asd
也不asd/123/1.txt
存在,因此它們被重定向到 index.php 並且工作正常。但是,如果我輸入 urlexample.com/asd.php
,它會嘗試查找asd.php
,當找不到它時,它會返回 404 而不是將請求發送到index.php
.如果不存在,有沒有辦法
asd.php
也被發送到?index.php``asd.php
根據您的附加評論,這聽起來可能是最理想的方式,儘管它不是一個漂亮的配置。
server { listen 80 default_server; access_log /path/to/site/dir/logs/access.log; error_log /path/to/site/dir/logs/error.log; root /path/to/site/dir/webroot; index index.php index.html; location / { try_files $uri $uri/ /index.php; } location ~ \.php$ { try_files $uri @missing; fastcgi_pass localhost:9000; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include /path/to/nginx/conf/fastcgi_params; } location @missing { rewrite ^ /error/404 break; fastcgi_pass localhost:9000; fastcgi_param SCRIPT_FILENAME $document_root/index.php; include /path/to/nginx/conf/fastcgi_params; } }