【问题标题】:Rewriting a URL to a query string on Apache and Nginx将 URL 重写为 Apache 和 Nginx 上的查询字符串
【发布时间】:2012-10-08 10:13:57
【问题描述】:

我正在尝试在两台单独的服务器上设置一些路径重写,一台在 Apache 上使用 mod-rewrite,另一台在 Nginx 上使用 HttpRewriteModule。我不认为我在尝试做任何太复杂的事情,但我的正则表达式技能有点欠缺,我真的可以使用一些帮助。

具体来说,我正在尝试将格式化的 URL 转换为查询字符串,以便链接格式如下:

http://www.server.com/location/

会指向这个:

http://www.server.com/subdirectory/index.php?content=location

格式化 URL 末尾的任何额外内容都应附加到查询字符串中的“内容”参数中,因此:

http://www.server.com/location/x/y/z

应该指向这个:

http://www.server.com/subdirectory/index.php?content=location/x/y/z

根据我所做的研究,我很确定这应该可以同时使用 Apache mod-rewrite 和 Nginx HttpRewriteModule,但我看不到让它工作。如果有人能给我一些关于如何将这些设置中的一个或两个的表达式放在一起的指示,我将不胜感激。谢谢!

【问题讨论】:

    标签: regex apache mod-rewrite url-rewriting nginx


    【解决方案1】:

    在 nginx 中,您在重写指令中匹配“/location”,捕获变量 $1 中的尾部字符串并将其附加到替换字符串。

    server {
    ...
    rewrite ^/location(.*)$ /subdirectory/index.php?content=location$1 break;
    ...
    }
    

    在 Apache 的 httpd.conf 中,这看起来非常相似:

    RewriteEngine On
    RewriteRule ^/location(.*)$ /subdirectory/index.php?content=location$1 [L]
    

    查看本页末尾的示例:https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html

    【讨论】:

    • 是否可以从:yoursite.com/something 重定向到 yoursite.com?content=something ?
    【解决方案2】:

    这可能是在 nginx 中做到这一点的最佳方式:

    location ^~ /location/ {
        rewrite ^/(location/.*)$ /subdirectory/index.php?content=$1 last;
    }
    

    更多详情见:

    【讨论】:

      【解决方案3】:

      对于 Apache,在文档根目录的 htaccess 文件中,添加:

      RewriteEngine On
      RewriteCond %{REQUEST_URI} !^/subdirectory/index\.php$
      RewriteRule ^(.*)$ /subdirectory/index.php?content=$1 [L]
      

      在 nginx 中,您首先要确保通过 /subdirectory/index.php 的请求,然后重写其他所有内容:

      location ~ /subdirectory/index\.php$ 
      { 
      } 
      
      location / 
      { 
          rewrite ^(.*)$ /subdirectory/index.php?content=$1 break; 
      }
      

      【讨论】:

      • 不需要两步。如果您使用正则表达式捕获“位置”,则对“子目录”的直接请求将始终通过。
      【解决方案4】:

      搜索字符串:(.+)/location/(.*)$

      替换字符串:$1/subdirectory/index.php?content=location/$2

      【讨论】:

      • 这将捕获第一组中的服务器名称,这对于重写是不必要的。
      猜你喜欢
      • 1970-01-01
      • 2015-04-27
      • 2019-02-13
      • 2021-01-06
      • 2011-09-09
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多