NGINX PHP子路径Location规则配置:特定路径与IP段访问控制需求
NGINX Access Control Configuration for Your Requirements
Alright, let's tackle this NGINX access control requirement step by step. I've dealt with similar scenarios before, so here's a clean, maintainable config that fits your needs perfectly:
Full Working Configuration
server { listen 80; server_name your-domain.com; root /path/to/your/webroot; # Allow internal IP range to access ALL paths first allow x.x.x.x/16; # Handle requests to /PROD/index.php with query parameter checks location ~ ^/PROD/index\.php$ { # For internal IPs: directly pass to PHP-FPM (bypasses further checks) if ($remote_addr ~* ^x\.x\.) { # Replace with your actual PHP-FPM endpoint (tcp or unix socket) fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; break; } # Allow global access ONLY if query string starts with /report (including subpaths) if ($args ~* ^/report(/.*)?$) { fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; break; } # Deny all other requests to /PROD/index.php deny all; } # Deny all other requests (only internal IPs are allowed via the top-level rule) deny all; }
Key Breakdown & Explanations
- Top-level IP Allow Rule: The
allow x.x.x.x/16;at the server level ensures your internal IP range bypasses all subsequent restrictions and can access every path on the server. NGINX processes allow/deny rules in order, so this takes highest priority. - Query Parameter Matching: Since NGINX's
locationdirective only matches the URI (not query strings), we use the$argsvariable to check if the query parameter starts with/report. The regex^/report(/.*)?$covers all your required subpaths:/PROD/index.php?/report/PROD/index.php?/report//PROD/index.php?/report/any-random-subpath
- PHP Handling: Adjust the
fastcgi_passvalue to match your actual PHP-FPM setup (use127.0.0.1:9000if you're using TCP instead of a unix socket). - Default Deny: The final
deny all;ensures any request not explicitly allowed (internal IPs or the report path) gets blocked.
Quick Testing Tips
- Verify global access works for the report path:
curl "http://your-domain.com/PROD/index.php?/report/test-subpath" # Should return 200 OK curl "http://your-domain.com/PROD/index.php?/non-report-path" # Should return 403 Forbidden - Test from your internal IP range to confirm you can access every path without restrictions.
内容的提问来源于stack exchange,提问作者Daniel Anner
相关产品推荐
相关产品推荐

