【问题标题】:setting up rewrite rules in nginx for location rewrites在 nginx 中为位置重写设置重写规则
【发布时间】:2017-05-24 07:16:29
【问题描述】:

我完全是 nginx 的菜鸟。我正在尝试在 nginx 中为位置重写设置一些规则。我想要实现的是:

1. no change
https://hello.domain.com/index.php --> https://hello.domain.com/index.php

2. subdomain needs to be included
https://hello.domain.com --> https://hello.domain.com/index.php?sub=hello

3. subdomain & folder structure needs to be included
https://hello.domain.com/dir1/15 --> https://hello.domain.com/index.php?sub=hello&path=dir1/15

4. requests to certain directories ( images, css, etc... ) need to be ignored
https://hello.domain.com/images/logo.png --> https://hello.domain.com/images/logo.png

我可以使用这个将子域放入变量 $sub

server_name ~^(?<sub>.+)\.domain\.com$;

我尝试使用 location 指令,但它仅适用于列表中的 #2 和 #3

location / {
        rewrite ^ /index.php?sub=$sub&path=$request_uri;
    }

任何帮助将不胜感激!!!

【问题讨论】:

  • 您可以使用try_files 处理案例#4,请参阅this answer 以获得指导。
  • 或者这个:if ($request_uri !~ "^/(?:images|css)") { rewrite ^ "/index.php?path=$request_uri&amp;sub=$sub" last; }
  • 我一直在读到不推荐使用if 条件句
  • 这也适用于location 范围,因为会进行内部重定向

标签: mod-rewrite nginx url-rewriting


【解决方案1】:

这可能会帮助您转发:

server_name ~^(?<sub>.+)\.domain\.com$;

location /images {
    # You can put this code in a snippet file and than include
    # it with e.g. `include assets.conf;` so you can use more
    # folders with longest prefix match blocks, which are more
    # efficient than regex blocks.

    # Tell the browser to cache this for one day
    expires 1d;

    # Just give the resource
    try_files $uri =404;
}

location /index.php {
    # PHP stuff goes here
}

location / {
    rewrite ^ /index.php?sub=$sub&path=$uri last;
}

【讨论】:

    猜你喜欢
    • 2016-05-30
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    • 2019-06-24
    • 2017-01-02
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多