首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >一封信的Nginx位置

一封信的Nginx位置
EN

Stack Overflow用户
提问于 2017-12-21 11:25:04
回答 1查看 114关注 0票数 0

如何为查询类型正确地使location重写

请求:

代码语言:javascript
复制
site.com/a/?f=qwerty 

改写为:

代码语言:javascript
复制
/a/?f=qwerty

请求:

代码语言:javascript
复制
site.com/b/?g=qwerty

改写为:

代码语言:javascript
复制
/b/?g=qwerty

请求:

代码语言:javascript
复制
site.com/anyshorttext/?h=qwerty 

改写为:

代码语言:javascript
复制
/special/?h=qwerty

我应用了以下解决方案:

代码语言:javascript
复制
server {

        location ~ /a/?(.*)$ {

            rewrite ^/([-\w]+) /a/?m=$1 break;

            index  index.php index.html index.htm;
                try_files $uri $uri/ =404;

                location ~ \.php$ {
                        include snippets/fastcgi-php.conf;
                        fastcgi_pass unix:/run/php/php7.1-fpm.sock;
                }
        }

        location ~ /b/?(.*)$ {

            rewrite ^/([-\w]+) /b/?m=$1 break;

            index  index.php index.html index.htm;
                try_files $uri $uri/ =404;

                location ~ \.php$ {
                        include snippets/fastcgi-php.conf;
                        fastcgi_pass unix:/run/php/php7.1-fpm.sock;
                }
        }

        location ~* ^/[a-zA-Z0-9/_$/]+$ {

            rewrite ^/([-\w]+) /special/?h=$1 break;

            index  index.php index.html index.htm;
                try_files $uri $uri/ =404;

                location ~ \.php$ {
                    include snippets/fastcgi-php.conf;
                    fastcgi_pass unix:/run/php/php7.1-fpm.sock;
                }
        }
  }

但是在这种情况下,请求只被转发到/special/

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-09 01:41:42

您的示例意味着查询字符串不会因每种情况而改变。如果是这样的话,您可以尝试以下方法:

代码语言:javascript
复制
map $uri $special_query {
    # $special_query will be true, for paths like: //site.com/xyz/?stuff
    ~^/[^/]+/$ $query_string;
}

server {
    location / {
        if ($special_query) {
            return 301 "/special/?$query_string";
        }
    }

    # these locations will override the default / location
    location = /a/ {}
    location = /b/ {}
    location = /special/ {}
}

该解决方案既不使用regex位置,也不重写它们,这都会给配置增加不必要的复杂性,并破坏自然的nginx流。(参见nginx作者Igor Sysoev:https://www.youtube.com/watch?v=YWRYbLKsS0I的可缩放配置)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47923928

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档