Muhammad Shahbaz
Muhammad Shahbaz

Reputation: 23

Redirection conflict in .htaccess

We want to redirect the blog folder to the news folder. For example: Anyone visiting ...

Below is my HTACCESS code.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.example\.co.uk [NC]
RewriteRule ^(.*)$ https://example.co.uk/$1 [L,R=301]
</IfModule>

# BEGIN WordPress
# The directives (lines) between `BEGIN WordPress` and `END WordPress` are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.


<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/news-blog-speaker/?$ [NC]
RewriteRule ^/blog/?$ /news/$1 [R=301,L]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Upvotes: 1

Views: 63

Answers (1)

MrWhite
MrWhite

Reputation: 45829

RewriteCond %{REQUEST_URI} !^/news-blog-speaker/?$ [NC]
RewriteRule ^/blog/?$ /news/$1 [R=301,L]

There are a few issues with the above directive:

  • In .htaccess the URL-path matched by the RewriteRule pattern does not start with a slash. So, it should be ^blog, not ^/blog.
  • You are only attempting to match /blog or /blog/. But you need to redirect /blog/<blog-title> - as stated in your question description.
  • Since you are not capturing anything in the RewriteRule pattern, the $1 backreference is always empty. You need to capture <blog-title> from the requested URL, but as mentioned above, you have made no attempt to do this.
  • The preceding condition (RewriteCond directive) that checks the request is not /news-blog-speaker is entirely superfluous, since you are already checking that the request is /blog. It can't be both.
  • Take note of the WordPress comment. You should not be manually editing the code between the # BEGIN/END WordPress comment markers.

Try the following instead before the # BEGIN WordPress section:

# Redirect "/blog/<blog-title>" to "/news/<blog-title>"
RewriteRule ^blog/([^/]+)/?$ /news/$1 [R=302,L]

# Redirect "/news-blog-presenters" to "/blog"
RewriteRule ^news-blog-presenters/?$ /blog [R=302,L]

The "conflict" is avoided by matching a non-empty <blog-title> and not simply /blog/. This seems to be what you require based on your stated requirements.

I assume /blog is not a physical directory, otherwise a request for /blog (no trailing slash) will trigger a redirect to /blog/ (by mod_dir).

Test first with 302 (temporary) redirects and only change to a 301 (permanent) - if that is required - after you have confirmed the redirect works as intended.

You will likely need to clear your browser cache before testing.

Upvotes: 1

Related Questions