Nginx别名请求重写后静态资源不可用问题求助
Fix Nginx Alias Static Resource Access with Rewrite to index.php
Let's break down the issue and fix your configuration step by step. The core problem here is that your current setup isn't properly distinguishing between existing static files and requests that need to be routed to index.php. When you uncommented that final location block (likely a global static resource handler), it clashed with your alias path, leading to broken static assets.
Working Configuration
Replace your existing location /csv-import block with this:
location /csv-import { alias /var/www/csv-import/public; # First check if the requested static file exists; serve it directly if it does try_files $uri $uri/ @csv_import_rewrite; # Handle PHP files within the alias path location ~ \.php$ { include snippets/fastcgi-php.conf; # $request_filename correctly maps to the aliased path (e.g., /var/www/csv-import/public/file.php) fastcgi_param SCRIPT_FILENAME $request_filename; fastcgi_pass unix:/run/php/php7.0-fpm.sock; } } # Named location to handle rewrite for non-static requests location @csv_import_rewrite { # Rewrite the path to pass the requested URI as the `q` parameter rewrite ^/csv-import/(.*)$ /csv-import/index.php?q=$1 last; }
Why This Works
try_filesPriority: Thetry_filesdirective first checks if the requested file ($uri) or directory ($uri/) exists in the aliased path (/var/www/csv-import/public). If it does, Nginx serves it directly—this fixes your static resource access.- Fallback Rewrite: Only when the static file/directory doesn't exist does Nginx pass the request to the
@csv_import_rewritenamed location, which routes it toindex.phpwith the requested URI as theqparameter. - Correct PHP Pathing: Using
$request_filenameensures that PHP-FPM gets the full, aliased path to the PHP file (no mismatches between the URL path and the actual filesystem path).
Alternative Simplified Version
If you prefer to avoid a named location, you can combine the rewrite directly in try_files:
location /csv-import { alias /var/www/csv-import/public; try_files $uri $uri/ /csv-import/index.php?q=$uri; location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_param SCRIPT_FILENAME $request_filename; fastcgi_pass unix:/run/php/php7.0-fpm.sock; } }
Key Pitfalls to Avoid
- Clashing Global Static Blocks: If you have a global
location ~* \.(css|js|png|jpg)$block elsewhere in your config, it might match requests before yourlocation /csv-importblock. To fix this, either adjust the order (more specific locations first) or add static file handling directly within yourcsv-importlocation. - Incorrect Path Variables: Never use
$document_root$fastcgi_script_namewithalias—this will generate an invalid filesystem path. Stick with$request_filenamefor alias setups.
内容的提问来源于stack exchange,提问作者Thomas Venturini
相关产品推荐
相关产品推荐

