【问题标题】:Rewriting URL with nginx my rewrite not working用 nginx 重写 URL 我的重写不起作用
【发布时间】:2017-09-12 20:10:58
【问题描述】:

我正在学习使用 nginx 重写 URL,想知道为什么下面的示例不起作用

我有以下网址

http://example.com/listings.php?city=Fayetteville

我有以下 URL 重新布线规则

rewrite ^/listings\.php\?city=(.*)$ http://google.com permanent;

当我访问 http://example.com/listings.php?city=Fayetteville 时,我应该将 URL 更改为 google.com,但没有任何反应。我在这里做错了什么?

【问题讨论】:

  • ? 开始的任何内容(查询字符串)都不是用于匹配rewritelocation 指令中的正则表达式的规范化URI 的一部分。
  • 您想对所有listing.php 执行此操作,还是仅在城市为费耶特维尔时执行此操作?正如@RichardSmith 提到的那样,请求 uri 没有得到参数
  • @TarunLalwani 我只是为了学习而玩它。但最后我希望example.com/listings.php?city=AnyCityName 变成example.com/AnyCityName 这可能吗?

标签: nginx


【解决方案1】:

是的,这是可能的。你会使用类似下面的东西

location = /listings.php {
    if ($arg_city) {
      rewrite ^(.*)$ /$arg_city;
   }
}

Edit-1

你可以像下面这样在你的配置中处理它

server {
        listen 80;
        listen [::]:80;

        root /var/www/html/example.com;
        index index.html index.htm index.nginx-debian.html index.php;

        server_name example.com www.example.com;

        location / {
                try_files $uri $uri/ =404;
        }

        location ~ \.php$ {
                set $test '';
            if ($request_uri ~* "^/listing\.php") {
                    set $test "listing";
                }

                if ($arg_city) {
                    set $test "$test-city";
                }

                if ($test = "listing-city")
                {
                    return 301 /$arg_city;
                }

                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        }

}

【讨论】:

  • 我在 "if (arg_city) {" 上遇到语法错误,所以我将其更改为 "if ($arg_city) {" 并且语法错误消失了。应该是这样吗?
  • 是的,抱歉打错了
  • 现在当我转到example.com/listings.php?city=Mobile 时,我得到一个 404。有点迷失了它应该如何工作。这是我第一次使用 URL 重写
  • 那是因为在外面你什么也没做。如果不是这种情况,您需要将其传递给 php-fpm
  • 这是相关的服务器块pastebin.com/6Kif04RF 如果我能看到一个例子,我应该弄清楚。在我的情况下,我们将如何使重写工作?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-03
  • 2018-04-04
  • 1970-01-01
  • 2016-12-18
相关资源
最近更新 更多