大网数据广告活动
服务器运维问答

Delete repeated subdirectory of url with redirect 301 in Nginx

· 52CE 我爱测

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://exam…

问题原文

原帖链接 · dertin · CC BY-SA 4.0

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.

已采纳解答

原帖链接 · Richard Smith · CC BY-SA 4.0

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.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-01-23)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。