Nginx重写规则配置:请求转发至PHP-FPM并设置例外规则
Nginx Rewrite Rule Setup: Forward All Requests to index.php Except Static Exceptions
Got it, let's walk through setting up this Nginx rewrite rule exactly as you need it. The key here is prioritizing the allowed static resources first, then catching everything else to forward to index.php—Nginx processes location blocks in order of priority, so we need to structure this correctly to avoid conflicts.
Here's the complete configuration you can drop into your server block:
server { listen 80; server_name yourdomain.com; # Replace with your actual domain root /var/www/your-site; # Update to your web root path index index.php; # Allow direct access to robots.txt (exact match only) location = /robots.txt { allow all; log_not_found off; # Optional: Skip logging if the file is missing } # Allow direct access to images/ and all subdirectories location ^~ /images/ { allow all; # Optional: Add cache headers for better performance expires 30d; add_header Cache-Control "public, immutable"; } # Catch all other requests and route to index.php location / { try_files $uri $uri/ /index.php?$query_string; } # PHP-FPM handler (adjust to match your server's setup) location ~ \.php$ { fastcgi_pass unix:/run/php/php8.2-fpm.sock; # Use TCP port like 127.0.0.1:9000 if needed fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } }
Let's break down what each part does:
location = /robots.txt: This is an exact match rule—only requests for/robots.txtwill trigger this. We tell Nginx to serve the file directly, and optionally skip logging 404s if the file doesn't exist (removelog_not_found offif you want those logs).location ^~ /images/: The^~modifier makes this a high-priority prefix match. Any request starting with/images/(including subdirectories like/images/blog/2024/) will be served as static files, bypassing the PHP-FPM handler entirely. The cache headers are optional but recommended for static assets to reduce server load.location /: This is the catch-all rule. If the request doesn't match the above two blocks, Nginx first tries to serve the requested file/directory directly. If that fails, it forwards the request toindex.phpalong with the original query string—perfect for single-page apps or CMS systems that handle routing via PHP.- PHP-FPM Block: This handles executing
index.php(and any other PHP files, though our catch-all ensures onlyindex.phpgets hit for most requests). Make surefastcgi_passmatches your server's PHP-FPM setup—some systems use a TCP port instead of a Unix socket.
Important Final Steps:
- Test your configuration for syntax errors with:
nginx -t - If the test passes, reload Nginx to apply changes:
systemctl reload nginx # Use `service nginx reload` on older distros
内容的提问来源于stack exchange,提问作者vagiz
相关产品推荐
相关产品推荐

