繁体   English   中英

如何在 Nginx 中将 url /id/slug (WordPress) 重写为 slug (Ghost)?

[英]How to rewrite url /id/slug (WordPress) to just slug (Ghost) in Nginx?

我正在尝试从 WordPress 迁移到自托管的 Ghost 博客。 在此过程中,我希望将我的帖子的 url 从https://example.com/categoryid/slug清理到https://example.com/slug Catogryid 似乎是包含 1-4 位数字的整数。

问题是我也有不想重写的网址

  1. 不要为 img 重写: https://example.com/content/images/2020/01/logo.png : https://example.com/content/images/2020/01/logo.png
  2. 重写帖子: https://example.com/1886/slug : https://example.com/1886/slug

我尝试过的:
这有效,但对于两个网址

rewrite ^(.*)(\/\d*\/)(.*)$ https://example.com/$3 redirect;

这应该与在线正则表达式测试仪匹配,但不起作用

rewrite \.*(com)(\/\d*\/)(.*)$ https://example.com/$3 redirect;

在重写规则之前和之后传递代理

location /content/ {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $http_host;
    proxy_pass example_ip ;
}

完整配置:

server {
    listen 80;
    listen [::]:80;
    server_name         www.example.com example.com;

    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

}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;


    # redirect /id/slug -> slug
    rewrite ^(.*)(\/\d*\/)(.*)$ https://example.com/$3 redirect;
    # redirect category -> tag
    rewrite (category\/)(.*)$ https://example.com/tag/$2 permanent;
    # redirect blog -> archive
    rewrite (blog\/)$ https://example.com/archive permanent;

    root /var/www/ghost/system/nginx-root; # Used for acme.sh SSL verification (https://acme.sh)
    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
    include /etc/nginx/snippets/ssl-params.conf;

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $http_host;
        proxy_pass http://example_ip;
    }

    location ~ /.well-known {
        allow all;
    }

    client_max_body_size 50m;

}

在 URL https://example.com/content/images/2020/01/logo.pnghttps://example.com/1886/slugrewrite指令看到的 URI 是/content/images/2020/01/logo.png/1886/slug

您需要重写在第一个路径元素中包含 1 到 4 位数字的 URI。

使用:

rewrite ^/\d+(/.*)$ $1 redirect;

或者:

rewrite "^/\d{1,4}(/.*)$" $1 redirect;

最后一个变体必须使用引号来保护嵌入的大括号字符。

有关详细信息,请参阅此文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM