You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nginx服务器中简洁重写含多GET参数的多PHP文件URL?

Efficient Nginx Rewrite Rules for Multiple PHP Files

Great question! Having to write separate rewrite rules for every single PHP file like character.php, place.php, or company.php gets tedious fast—luckily, Nginx's regex support lets us handle all these cases with a single, flexible rule.

Option 1: Catch-All Regex Rule (for any matching PHP file)

If your URL structure follows the pattern /{resource}/{details} (e.g., /character/123, /place/waterfall) and each resource maps directly to a PHP file of the same name, you can use a regex capture group to dynamically target the right file:

rewrite ^/([a-z]+)/(.*)$ /$1.php?path=$2 last;

Let's break this down:

  • ^/([a-z]+)/(.*)$: The first capture group ([a-z]+) grabs the resource name (like character or place), and (.*) captures everything after it (the subpage details).
  • /($1).php?path=$2: Rewrites the request to the corresponding PHP file, passing the captured subpage details as a query parameter (adjust the query part to match your existing rule's logic if needed).

To avoid accidentally rewriting requests to non-existent PHP files, add a check to verify the file exists first:

if (-f $document_root/$1.php) {
    rewrite ^/([a-z]+)/(.*)$ /$1.php?path=$2 last;
}

Option 2: Restricted Rule (for specific resources only)

If you want to limit the rule to only your intended files (to prevent unintended matches like /randomfile/xyz), explicitly list the allowed resources in the regex:

rewrite ^/(character|place|company)/(.*)$ /$1.php?path=$2 last;

This way, only requests targeting character, place, or company get rewritten—just add new resource names to the pipe-separated list as you create more PHP files (e.g., character|place|company|item).

Option 3: Using try_files (More Nginx-idiomatic)

For a more efficient approach (Nginx recommends avoiding if when possible), use a location block with try_files:

location ~ ^/([a-z]+)/(.*)$ {
    try_files $uri $uri/ /$1.php?path=$2;
}

This first tries to serve an actual file or directory at the requested path, and if that fails, it rewrites to the corresponding PHP file—perfect for clean URL structures.

Quick Notes

  • If your resource names include uppercase letters or numbers, adjust the regex to [a-zA-Z0-9]+ or \w+ (matches letters, numbers, and underscores).
  • Make sure to test the rules with nginx -t before reloading to catch syntax errors!

This approach will save you from writing duplicate rules every time you add a new resource file for your game.

内容的提问来源于stack exchange,提问作者Serhat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:02:14