仅当 .php 在 URL 中时,Nginx 才下载 PHP 文件

Mat*_*w A 8 php nginx

我知道这是一个受欢迎的问题,但我还没有发现任何人有类似的问题。只要 .php 扩展名不在 url 中,我就可以提供 PHP 文件。例如:

如果我去,我会得到localhost我的 index.php 文件。如果我去localhost/index.php我下载文件。这是我的配置:

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /usr/share/nginx/html;
    index index.php index.html index.htm;

    # Make site accessible from http://localhost/
    server_name localhost;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        try_files $uri $uri/ =404;
        # Uncomment to enable naxsi on this location
        # include /etc/nginx/naxsi.rules
    }

    # Only for nginx-naxsi used with nginx-naxsi-ui : process denied requests
    #location /RequestDenied {
    #   proxy_pass http://127.0.0.1:8080;    
    #}

    error_page 404 /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny all;
    }
}
Run Code Online (Sandbox Code Playgroud)

我对这个问题很困惑,我想知道是否有人有这方面的经验。

Oli*_*Oli 4

如果这有时有效(所以你知道 PHP-FPM 已启动并正在工作),我会非常确定这是一个 nginx 问题。我对 PHP 位置块中的一些规则表示怀疑。他们可能会破坏某些 URL,导致 nginx 转储。

你只需要两行来捕获目录索引:

location ~ \.php$ {
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    include fastcgi_params;
}
Run Code Online (Sandbox Code Playgroud)

将该位置剥离回原来的位置,重新加载 nginx,看看会发生什么。

如果您需要重写(Wordpress 中的漂亮 URL 等),您需要添加如下内容

location / {
        try_files $uri $uri/ /index.php?$args;
}
Run Code Online (Sandbox Code Playgroud)

但只有在标准 URL 正常工作后才可以这样做。

  • 我做了一些改变,但一开始并没有起作用。然后我删除了浏览器上的缓存并且它起作用了。感谢您的时间!:) (2认同)