nginx重写子网址

时间:2015-12-18 12:04:35

标签: nginx rewrite

如何解决此问题:我想设置nginx conf文件以符合以下条件:

http://www.example.com/site1/article/index.php?q=hello-world - > http://www.example.com/site1/article/hello-world

htt://www.example.com/site2/article/index.php?q = goodbye-world - > HTTB://www.example.com/site2/article/goodbye-world

htt://www.example.com/site3/article/index.php?q = open-new-world - > HTTB://www.example.com/site3/article/open-new-world

在example.com之后有多个网站,我想通过使用nginx配置让网址看起来很干净。

但我的以下配置不起作用。有人帮帮我吗?

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

root /var/www/example.com/public_html;
index index.php index.html index.htm;

server_name www.example.com;     
location ~ /article/ {
    try_files $uri /site1/article/index.php?q=$1;

    location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            include fastcgi_params;
    }
}

}

1 个答案:

答案 0 :(得分:0)

您希望客户端显示/xxx/article/yyy之类的网址,然后在内部将其重写为/xxx/article/index.php?q=yyy

您需要捕获源URI的组件才能在以后使用它们。你的问题中有一个$1,但你错过了表达式来实际给它一个值。通过最少的更改次数,可以实现:

location ~ ^(.*/article/)(.*)$ {
    try_files $uri $1index.php?q=$2;
    location ~ \.php$ { ... }
}

但是,您不需要为PHP使用嵌套位置,只要PHP正则表达位置在上面上面其他正则表达位置,它就会处理所有php文件。例如:

location ~ \.php$ { ... }

location ~ ^(.*/article/)(.*)$ {
    try_files $uri $1index.php?q=$2;
}