允许本地主机;全部拒绝;对于所有人,尽管 "index.php" 和“/”

allow localhost; deny all; for all despite "index.php" and "/"

我正在尝试限制对 Web 服务器上的 .php 文件的直接访问。

已使用 allow localhost;deny all;。但是,这也限制了对 index.php.

的访问

如何克服这个问题?有没有类似IF conditions的东西?

我的配置:

if ($request_uri ~* "^(/)index\.php$") {
    return 301 ;
}

location / {
try_files $uri $uri/ /index.php?$args; 

    rewrite ^/(\w+)$       /?system=       break;
    rewrite ^/(\w+)/(\w+)(/.)*$ /?system=&id= break;
    rewrite ^/(.*)/$ / permanent; 

location ~ \.php$ {
       try_files  $uri =404;

       fastcgi_split_path_info ^(.+\.php)(/.+)$;
       #fastcgi_pass 127.0.0.1:9000;
       fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
       fastcgi_index index.php;
       include fastcgi_params;

       fastcgi_param PHP_VALUE "auto_prepend_file=/usr/share/nginx/html/web/config.php";
    }

}

通常的做法是将 RewriteRule 添加到 .htaccess 文件。这使得您可以根据需要将所有流量重定向到 index.php

此解决方案甚至允许您将请求的 URL 添加为 URL 参数,因此可以在 index.php 中将其作为 $_GET 变量访问。

由于 .htaccess 只是 Apache 服务器的解决方案,因此不能在此处一对一应用。 NGINX 网站上的这篇博客 post 解释了它是如何在 NGINX 上完成的:https://www.nginx.com/blog/creating-nginx-rewrite-rules/

不是匹配所有 PHP 个文件,而是只匹配 index.php 并拒绝所有其他文件,如下所示:

location = /index.php {
  try_files  $uri =404;

  fastcgi_split_path_info ^(.+\.php)(/.+)$;
  #fastcgi_pass 127.0.0.1:9000;
  fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
  fastcgi_index index.php;
  include fastcgi_params;

  fastcgi_param PHP_VALUE "auto_prepend_file=/usr/share/nginx/html/web/config.php";      
}

location ~ \.php$ {
  return 301 $scheme://$http_host/index.php;
}

如果您希望允许服务器发帖给自己,请为 URI 添加以下内容

location = /post.php {
  allow 127.0.0.1/24;
  deny all;

  try_files  $uri =404;

  fastcgi_split_path_info ^(.+\.php)(/.+)$;
  #fastcgi_pass 127.0.0.1:9000;
  fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
  fastcgi_index index.php;
  include fastcgi_params;

  fastcgi_param PHP_VALUE "auto_prepend_file=/usr/share/nginx/html/web/config.php";      
}

编辑:替代配置

server {
  listen 80;

  location = /index.php {
    try_files  $uri =404;

    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    #fastcgi_pass 127.0.0.1:9000;
    fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;

    fastcgi_param PHP_VALUE "auto_prepend_file=/usr/share/nginx/html/web/config.php";      
  }

  location ~ \.php$ {
    return 301 $scheme://$http_host/index.php;
  }
}

server {
  listen 127.0.0.1:81;

  location / {
    try_files $uri $uri/ /index.php?$args; 
  }

  location ~ \.php$ {
    try_files  $uri =404;

    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    #fastcgi_pass 127.0.0.1:9000;
    fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;

    fastcgi_param PHP_VALUE "auto_prepend_file=/usr/share/nginx/html/web/config.php";      
  }
}

然后需要将本地请求定向到端口 81,即:

curl http://localhost:81/myscript.php