大网数据广告活动
服务器运维问答

Clean URLs and php extension on nginx

· 52CE 我爱测

I've looked at dozens of other questions and references on the web - and by all my calculations, my setup should work, but it doesn't. I have nginx installation with php-fpm. If I try to access a .php file, it runs correctly and …

问题原文

原帖链接 · Aleks G · CC BY-SA 3.0

I've looked at dozens of other questions and references on the web - and by all my calculations, my setup should work, but it doesn't.

I have nginx installation with php-fpm. If I try to access a .php file, it runs correctly and I get the correct results. I got this in my config file:

location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
}

Now, I want to setup my web app so that /somedir/file automatically executes /somdir/file.php while still displaying /somdir/file in the browser's address bar. So I modified my config to contain the following:

location / {
    try_files $uri $uri/ $uri.php?query_string
}

This kind of works, that is, the server does access the .php file. Yet, instead of executing it using the existing location ~ \.php$ block above, it simply spits the php source code as the download into the browser. If I append the .php manually to the requested URL, then the php is executed.

It feels as if once the server matches try_files to $uri.php, it then does not do another pass at locations to see that what it needs to do with the php files. I tried putting the php block above and below the location /, but it makes no difference.

How can I get the php to be executed?

社区高分解答

原帖链接 · martintama · CC BY-SA 3.0

Did you try with the rewrite directive? For example:

location / {
    try_files $uri $uri/ @extensionless-php;
    index index.html index.htm index.php;
} 

location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
}

location @extensionless-php {
    rewrite ^(.*)$ $1.php last;
}

Source: http://www.tweaktalk.net/60/nginx-remove-php-file-extension-from-url

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-02-18)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。