WP & Nginx: redirect post URLs containing '/folder/' but not image URLs containing '/folder/'

StackOverflow https://stackoverflow.com/questions/23674156

문제

On a Wordpress / Nginx site, I am removing / redirecting a section of articles from our website, and would like to redirect all urls of this content to another section of the site.

I've got this much working just great (see below), but unfortunately the name of an image folder also contains the string I'm using to catch the redirect.

We want for these images to show still. Here are a few example URLs of the desired behavior I'm trying to achieve:

  1. http://www.website.com/contenttoberemoved/ -- redirect to http://www.website.com/other/section/
  2. http://www.website.com/contenttoberemoved/an-article/ -- redirect to http://www.website.com/other/section/
  3. http://www.website.com/wp-content/themes/theme-name/custom/contenttoberemoved/images/image-name.jpg -- perform NO redirect

And here is the current Nginx configuration:

# Addresses URL #1 above
    if ( $request_filename ~ contenttoberemoved/ ) {
        rewrite ^(.*) http://www.website.com/category/articles/ permanent;
    }

# Addresses thousands of URLs with the structure of #2 above
    if ( $request_filename ~ contenttoberemoved/.+ ) {
        rewrite ^(.*) http://www.website.com/category/articles/ permanent;
}

# No idea what to do to address #3

Here is the full server block:

server {
    server_name website.com www.website.com;

    access_log   /var/log/nginx/access.log;
    error_log    /var/log/nginx/error.log error;

    root /usr/share/nginx/www;
    index index.php;

    location / {
            try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
            try_files $uri =404;
            include fastcgi_params;
            #fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_pass 127.0.0.1:9000;
    }

    # redirects

        if ( $request_filename ~ contenttoberemoved/ ) {
            rewrite ^(.*) http://www.website.com/category/articles/ permanent;
        }
        if ( $request_filename ~ contenttoberemoved/.+ ) {
            rewrite ^(.*) http://www.website.com/category/articles/ permanent;
        }

    #many page-level redirects below....
}

How can I make the redirect instructions broad enough to encompass example URLs #1 & #2 above, but specific enough to not include images (or really anything other than the posts I'm trying to target)?

Thanks!

도움이 되었습니까?

해결책

For your URLs there is no need to use if and regexps. Simple location will be enough:

location ^~ /contenttoberemoved/ {
    return 301 /category/articles/;
}

That's all.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top