[英]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 位數字的整數。
問題是我也有不想重寫的網址
https://example.com/content/images/2020/01/logo.png
: https://example.com/content/images/2020/01/logo.png
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.png
和https://example.com/1886/slug
, rewrite
指令看到的 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.