Warm tip: This article is reproduced from serverfault.com, please click

Delete repeated subdirectory of url with redirect 301 in Nginx

发布于 2021-01-13 23:15:02

I have to delete a subdirectory that has been duplicated in several URLs of my site, through a permanent redirect 301.

I'm needing help with the Nginx configuration.

For example:
http://example.com/foo/DIR/DIR/bar --> http://example.com/foo/DIR/bar

location ~ ^(.*)/DIR/DIR(.*)$ {
    rewrite ^(.*)$ /DIR/$1 last;
    break;
}

My current nginx server configuration:

server {

    listen 443 ssl http2 fastopen=500 reuseport;
    listen [::]:443 ssl http2 fastopen=500 reuseport ipv6only=on;
    server_name www.example.com;
    resolver 1.1.1.1 1.0.0.1 valid=300s;

    charset utf-8;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    include /etc/nginx/snippets/diffie-hellman;

    root /var/www/webdisk/example.com/htdocs;

    autoindex off;
    index load.php index.php index.html;

    include /etc/nginx/snippets/security;
    include /etc/nginx/snippets/expires;
    include /etc/nginx/snippets/error_pages;
    include /etc/nginx/snippets/pagespeed;

    location ~ \.php$ {
        include /etc/nginx/fastcgi.conf;
        fastcgi_pass unix:/run/php/php7-fpm.sock;
        fastcgi_send_timeout 1200s;
        fastcgi_read_timeout 1200s;
        fastcgi_connect_timeout 75s;
    }

# TODO: http://example.com/foo/DIR/DIR/bar --> http://example.com/foo/DIR/bar

    location ~* ^/(.+)$ {
        if (-f $document_root/public/prov/$1.html) {
            rewrite ^(.+)$ /public/prov/$1.html last;
            break;
        }
        if (!-e $request_filename){
            rewrite ^(.+)$ /load.php?request=$1 last;
            break;
        }
    }

}

I hope you can help me, to understand how this kind of redirection should be done.

P.S. After the redirection, it must be processed under the latest directive towards the PHP Framework. /load.php?request=$1

Thank you.

Questioner
dertin
Viewed
0
Richard Smith 2019-01-24 20:30:51

To redirect with a 301 response, you need to use rewrite...permanent or return 301 ....

To remove part of a URI, you need to capture those parts of the URI both before and after the part to be removed - much like the regular expression in your location statement.

For example:

rewrite ^(.*)/DIR/DIR(.*)$ $1/DIR$2 permanent;

See this document for details.