php - Nginx - 将包括 .php 在内的所有请求重定向到单个 PHP 脚本?

标签 php nginx

我已经在谷歌上搜索了一段时间,但似乎找不到解决方案。

目前,我在 Nginx 上设置了一个配置文件,用于将所有请求(无论文件扩展名如何)发送到单个 index.php 文件。但是,它会忽略以 .php 结尾的请求,如果不存在,则会抛出 404,如果存在,则尝试执行它。

如何配置 Nginx 将 .php 请求也发送到 index.php 文件,以便我可以使用它来处理所有文件请求,而不仅仅是非 PHP 文件?

我的配置文件当前如下所示:

server {
        listen 80;
        listen 443;

        ssl on;
        ssl_certificate /somecrt.crt;
        ssl_certificate_key /somekey.key;

        root /sites/;
        index index.php;

        server_name somesite.net;

        access_log /sites/logs/access.log;
        error_log /sites/logs/error.log;

        location ~ /\. { deny all; }

        location / {
                # First attempt to serve request as file, then
                # as directory then fall back to index.php
                try_files $uri $uri/ /index.php?$args;
                # Uncomment to enable naxsi on this location
                # include /etc/nginx/naxsi.rules
        }

        location ~ \.php$ {
                try_files $uri /index.php?$args =404;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                # fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                include fastcgi_params;
        }

}

最佳答案

经过更多谷歌搜索“nginx: Map single static URL to a PHP file”帮助我找到了解决方案。所以现在新的配置是:

server {
    listen 80;
    listen 443;

    ssl on;
    ssl_certificate /somecrt.crt;
    ssl_certificate_key /somekey.key;

    root /sites/;
    index index.php;

    server_name somesite.net;

    access_log /sites/logs/access.log;
    error_log /sites/logs/error.log;

    location ~ /\. { deny all; }

    location / {
            include fastcgi_params;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_param SCRIPT_FILENAME $document_root/index.php;

    }

}

使用此配置,所有请求都将发送到单个index.php。

当然,这将包括静态文件,例如图像文件,这可能会影响 Nginx 服务器的性能。在这种情况下,如果您想排除某些类型的请求,您可能需要在其前面添加另一个位置 block 。

例如,要排除 jpg 和 gif:

   location ~ \.(jpg|gif) {
           try_files $uri =404;
   }

关于php - Nginx - 将包括 .php 在内的所有请求重定向到单个 PHP 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47541457/

相关文章:

php - SSL:使用 PHP(没有 phpseclib)将私钥与证书匹配

php - 在 WordPress 函数文件中包含 JS(使用 PHP)的最佳实践

PHP pcntl模块安装

php - 如果相关表上存在id,如何查询表不包含数据?

php - HTMLPurifier 破坏图像

ssl - 带有 OpenSSL 1.0.2 的最新 Nginx 仍然无法提供 http/2

php - 在 Nginx/PHP-FPM 上使用 PHP ob_flush 刷新输出

ruby - 如何将 sinatra 部署到 aws ec2 ubuntu 服务器?

ruby-on-rails - 在 Rails 2.3.12 和 HTTPS 中安装机架应用程序失败

SSL:错误:0B080074:x509 证书例程:X509_check_private_key: key 值不匹配但模数匹配