【问题标题】:Nginx routing (rewrite)Nginx 路由(重写)
【发布时间】:2018-09-12 01:46:29
【问题描述】:

我正在从 Apache (htaccess) 切换到 Nginx,但我不知道如何让重写工作。

每个文件夹都有一个.htaccess 和一个index.php

test1/
   - .htaccess
   - index.php
test2/
   - .htaccess
   - index.php

.htaccess

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?rt=$1 [L,QSA]

index.php

switch ($_GET['rt']) {
  default:
    echo 'default page';
    break;

  case 'page2':
    echo 'page2';
    break;
}

如果用户访问 URL example.com/test1,它会显示“默认页面”(实际 URL 将是 example.com/test1/index.php)。

或者如果他们转到example.com/test2/page2(实际网址为example.com/test2/index.php?rt=page2),页面将显示“page2”。

我认为可以工作的 Nginx 块:

location /test1 {
    try_files $uri $uri/ index.php?rt=$uri;
}

【问题讨论】:

    标签: php .htaccess nginx


    【解决方案1】:

    您可以在 Nginx 块中尝试以下代码:

      location / {
          try_files $uri $uri/ @rewrite;
      }
    
      location @rewrite {
          rewrite ^/(.*)$ /index.php?rt=$1 last;
      }
    

    这会将路径如:“domain.com/test”重写为 domein.com/index.php?rt=test。

    将“domain.com/test/test2”之类的另一部分添加到 domein.com/index.php?rt=test/test

    希望对你有帮助。

    更多关于 Nginx 重写在这里:https://www.nginx.com/blog/creating-nginx-rewrite-rules/

    【讨论】:

    • 不是我想要做的。如果用户转到example.com/test1/page2,它将与转到example.com/test1/index.php?rt=page2 相同
    • 啊哈,我明白了。在这种情况下,只需将: rewrite ^/test1/(.*)$ /index.php?rt=$1 last;在 test1 的 location 块中也可以工作。
    • 不起作用。 rewrite ^/(.*)$ /index.php?rt=$1 last; 不断回到 example.com 的索引,所以我尝试了 rewrite ^/(.*)$ /test1/index.php?rt=$1 last; 但这只是去了 example.com/test1/
    • 尝试在 rewrite: "^/test1/(*.)$" 中设置 /test1,这会告诉 nginx 触发 example.com/test1 上的规则
    • rewrite ^/test1/(.*)$ /test1/index.php?rt=$1 last; 有效!谢谢
    猜你喜欢
    • 2015-04-03
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 2017-06-21
    • 2018-09-09
    • 1970-01-01
    • 2018-12-12
    • 1970-01-01
    相关资源
    最近更新 更多