Nginx重写规则配置:如何避免非指定PHP文件被直接执行?
Hey there, let's sort out this Nginx rewrite problem you're stuck on! The core issue here is Nginx's location matching priority—you need to explicitly allow the safe paths/files first, block unauthorized PHP execution, and then apply your rewrite rule. Here's a step-by-step solution that should fix your config.php bypass issue:
Key Configuration Breakdown
We'll structure the rules in order of Nginx's matching priority (highest to lowest) to ensure nothing slips through:
Exact match for loader.php
This ensuresloader.phpis always executed directly, without being caught by other rules.location = /loader.php { include fastcgi_params; fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # Update to your PHP-FPM socket/path fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; }Priority match for /images/ directory
Using^~tells Nginx to prioritize this prefix match over any regular expression locations, so all requests under/images/are served normally—including PHP files inside this directory if needed.location ^~ /images/ { root /path/to/your/webroot; # Replace with your actual website root directory # Uncomment below if you need to execute PHP files inside /images/ location ~ \.php$ { include fastcgi_params; fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } }Block all other PHP files
This rule catches any PHP request that wasn't matched by the above two rules, preventing direct execution of files likeconfig.php.location ~ \.php$ { deny all; return 403; # Optional: Returns a "Forbidden" error instead of just blocking }Rewrite all remaining requests
Finally, any request that isn't forloader.phpor under/images/gets rewritten to your loader script.location / { rewrite ^/(.*)$ /loader.php?control=$1 last; }
Why This Works
Your original issue happened because Nginx was matching the regular expression rule for .php files before your rewrite rule. By ordering the rules from highest priority (exact/prefix matches) to lowest, we:
- First allow the safe files/directory
- Block all other PHP execution
- Then apply the rewrite for everything else
Quick Testing Steps
- Validate your config with
nginx -tto catch syntax errors - Reload Nginx with
systemctl reload nginx(orservice nginx reloaddepending on your OS) - Test accessing
yourdomain.com/config.php—it should now return a 403 instead of executing the file, whileyourdomain.com/anything-elsegets rewritten toloader.php?control=anything-else
内容的提问来源于stack exchange,提问作者J. Smith

