How to do 301 redirect to Sub page using htaccess file?

I have 2 URLs. Basically page and sub page as below.

  • http://example.com/services
  • http://example.com/services/service-1

I want to add a 301 redirect rule in .htaccess file so that when someone opens the page:

http://example.com/services

it should redirect to its sub page:

http://example.com/services/service-1

I tried creating a rule in .htaccess file but it is going into redirection loop as its sub page. Below is my code for .htaccess file:

Redirect 301 /services /services/service-1

Update: Below is entire htaccess file code

RewriteRule ^for-patients$ /for-patients/children [R=302,L]

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

1 Answer
1

Redirect 301 /services /services/service-1

This results in a redirect loop because the mod_alias Redirect directive is prefix matching. So, the source path /services matches the redirected path /services/services-1, etc. etc.

However, since you are already using mod_rewrite (as part of WordPress), you should also perform this redirect using mod_rewrite (as opposed to mod_alias). Different modules execute at different times during the request (mod_rewrite before mod_alias), despite the apparent order in .htaccess, so this can lead to some unexpected conflicts.

So, instead, try the following before your existing WordPress front-controller (ie. before the # BEGIN WordPress comment):

RewriteRule ^services$ /services/service-1 [R=302,L]

This matches the URL /services only. Note there is no slash prefix on the RewriteRule pattern when used in .htaccess.

This is a temporary (302) redirect. Change this to a 301 if this is intended to be permanent, but only after you have confirmed it is working OK. (301s are cached hard by the browser by default, so can make testing problematic.)

UPDATE: To make the above work with (or without) a trailing slash on the end of the requested URL then change the above to:

RewriteRule ^services/?$ /services/service-1 [R=302,L]

And if your target URL should have a trailing slash as well, then append this on the substitution. ie. /services/service-1, otherwise WordPress will either issue another redirect or you potentially create a duplicate content issue.

Leave a Comment