【问题标题】:How to implement rewrite in nginx based on existence of a specific argument in the URI?如何根据URI中特定参数的存在在nginx中实现重写?
【发布时间】:2016-07-31 17:51:57
【问题描述】:

最初的目标:我希望尝试打开页面http://example.com/something的用户被重定向到http://example.com/index.php?download=something

原始目标示例: 访问源 URL(http://something.com/18AhPyB&p=CdATyJnFMw1gl9Z) 的用户被重定向到 目标 URL(http://something.com/index.php?download=18AhPyB&p=CdATyJnFMw1gl9Z)

我在 Nginx 配置中所做的事情

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

该方法的问题:如果有人试图打开 主页(http://something.com),则会出现错误。我的理解是我无意中拨打了所有电话以进行重定向。

问题:如何只使用“&p”参数制作网址以进行重定向?请帮忙。

【问题讨论】:

    标签: php regex redirect nginx url-rewriting


    【解决方案1】:
    ^\/(.*&p=.*)$
    
    • ^ 是字符串开始。
    • \/ 是转义字符/
    • () 捕获的组。
    • .* 匹配任意长度的字符。
    • &p= 匹配 &p= 字面意思。
    • $ 是字符串结尾。

    Regex101 (here) 非常适合创建和调试正则表达式。

    【讨论】:

      【解决方案2】:

      据我了解,只有当参数 download 存在时,您才需要重定向。然后你必须写一个这样的位置部分:

      index index.php;
      location / {
          try_files $uri $uri/ /index.php;
      
          if ($arg_p) {
              return 301 http://something.com/index.php?download=$request_uri;
          }
      
          location = /index.php {
      
              fastcgi_pass   127.0.0.1:6969;
              fastcgi_param  SCRIPT_FILENAME /var/www$fastcgi_script_name;
              include        fastcgi_params;
          }
      }
      

      记得将端口更改为您的 php-fpm 或任何您用来处理 php 代码的端口。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-27
        • 1970-01-01
        • 2014-02-08
        • 2021-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多