如果URL包含特定单词,nginx如何重定向到wordpress文件夹

时间:2019-02-28 08:19:57

标签: nginx nginx-location nginx-config

首先,我的域根配置为使用反向代理重定向到Angular网页,该反向代理重定向到本地ip /端口,其工作原理很像。现在,如果我要覆盖根规则(如果URL包含要重定向到wordpress文件夹的/blog),问题就到了。目前,通过此配置,我可以访问wordpress,但只能访问example.com/blog/wp-admin/index.php之类的特定网址,但是如果我访问example.com/blog仍会转到有角度的应用程序。我已经按照以下方式配置了我的nginx(我必须说这是我第一次配置网络服务器):

server {
    listen [::]:443 ssl http2;
    listen 443 ssl http2;
    server_name example.com www.example.com;

    client_max_body_size 100M;
    root /var/www;
    index index.php index.html index.htm index.nginx-debian.html;
    autoindex off;

    location ~ /blog(.*)+/(.*)$ {
        try_files $uri $uri/ /blog/index.php?$args /blog/index.php?q=$uri&$args;
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
   }

    location / {
        proxy_pass http://127.0.0.1:4000;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-NginX-Proxy true; proxy_redirect off;
        http2_push /var/www/example_frontend/dist/example-frontend/favicon.ico;
        http2_push /var/www/example_frontend/dist/example-frontend/manifest.json;
    }

    location /robots.txt {
        alias /var/www/example_frontend/robots.txt;
    }

    location /sitemap.xml {
        alias /var/www/example_frontend/sitemap.xml;
    }

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
}


server {
    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80;
    server_name example.com www.example.com;
    return 404; # managed by Certbot
}

如果我停止我的角度应用程序,它会很好地工作,所以我认为我首先需要触发/ blog位置,但是我尝试了所有可能的形式,但没有结果。有人看到问题了吗?我以为首先触发了第一个规则,但似乎没有。

谢谢。

如果需要,我可以附加任何其他配置文件;)

1 个答案:

答案 0 :(得分:1)

URI /blog与您的location的正则表达式不匹配,这需要在URI中的某个地方附加一个/才能匹配。

简单的解决方案是:

location /blog {
    try_files $uri $uri/ /blog/index.php?q=$uri&$args;
    ...
}

以上内容将与/blog/blog/匹配,但也将与/blogx匹配(这可能是不希望的)。


您可以使用修改后的正则表达式,例如:

location ~ ^/blog(/|$) {
    try_files $uri $uri/ /blog/index.php?q=$uri&$args;
    ...
}

最有效的解决方案是使用前缀位置,但要进行更多键入:

location /blog {
    return 301 /blog/;
}
location /blog/ {
    try_files $uri $uri/ /blog/index.php?q=$uri&$args;
    ...
}

有关更多信息,请参见this document顺便说一句,您的try_files语句包含一个虚假参数。

相关问题