【问题标题】:Nginx - Redirecting all request including .php to single PHP script?Nginx - 将包括.php在内的所有请求重定向到单个PHP脚本?
【发布时间】:2017-11-28 21:47:02
【问题描述】:

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

目前我在 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;
        }

}

【问题讨论】:

  • 尝试从try_files $uri /index.php?$args =404;中删除$uri(对于php文件),$uri是你的PHP文件,如果文件存在,你尝试在index.php之前访问它。
  • 你有index.php文件使用的资源文件吗?我不确定我是否理解为什么文档根目录中会有其他 .php 文件。
  • @RichardSmith,总是有可能在同一个文件夹中有其他 php,但我相信你现在知道了,但是对于仍然想知道原因的其他人,可能有一个 lib。 php 或 config.php 在同一文件夹中,不用于浏览。

标签: php nginx


【解决方案1】:

在谷歌搜索后“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 服务器性能的静态文件,例如图像文件。在这种情况下,如果您想排除某些类型的请求,您可能需要在其前面添加另一个位置块。

例如,排除 jpg 和 gif:

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

【讨论】:

    猜你喜欢
    • 2016-12-18
    • 1970-01-01
    • 2019-01-30
    • 2015-11-26
    • 2014-09-04
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 2015-11-03
    相关资源
    最近更新 更多