TransWikia.com

Nginx rewrite: replace - with /

Server Fault Asked by Tomas Morgan on December 7, 2020

I set up ghost blogging platform.
It doesn’t allow to insert «/» signs in article links, but I want them to appear in my links, so I want them to be fixed with nginx rewrites.

The link in a browser looks like this:

http://blog.site.com/stuff-life/

And I want it to be like this:

http://blog.site.com/stuff/life/

It goes without saying that it should be applied for a number of links starting from “stuff-*”, not for one.

I found this, but it’s way too complicated for me:

http://nginx.org/en/docs/http/ngx_http_rewrite_module.html

My config looks like this:

server {
listen 80;
server_name blog.site.com;
access_log /var/log/nginx/ghost.log;
error_log /var/log/nginx/ghost.error.log;
    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header HOST $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://127.0.0.1:2368;
        proxy_redirect off;
        }
}

So how I do a rewrite in my case? Thanks.

Update.

Now I try to do it this way:

server {
listen 80;
server_name somesite.com;
access_log /var/log/nginx/ghost.log;
error_log /var/log/nginx/ghost.error.log;
location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header HOST $http_host;
    proxy_set_header X-NginX-Proxy true;

    proxy_pass http://127.0.0.1:2368;
    proxy_redirect off;
}


location /stuff- {
    rewrite ^/stuff-(.*) http://$server_name/stuff/$1 permanent;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header HOST $http_host;
    proxy_set_header X-NginX-Proxy true;

    proxy_pass http://127.0.0.1:2368;
    proxy_redirect off;
}


}

And it looks like nginx is passing rewrited links to ghost. And I get 404 page.

2 Answers

And the answer is:

server {
# <...>

rewrite ^/stuff-(.*) /stuff/$1 permanent;
rewrite ^/stuff/(.*) /stuff-$1;

location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header HOST $http_host;
    proxy_set_header X-NginX-Proxy true;

    proxy_pass http://127.0.0.1:2368;
    proxy_redirect off;
}
}

Answered by Tomas Morgan on December 7, 2020

You need to make sure the links are in correct format in your software also. nginx cannot rewrite links in the pages themselves, you need to handle those other way.

However, making nginx show /stuff-life when accessing /stuff/life can be done like this:

location ~ /stuff/(?<part>.+)$ {
    rewrite ^ /stuff-$part last;
}

Answered by Tero Kilkanen on December 7, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP