Using .htaccess to change directory in url

14,893

The problem here is that RewriteRule ^blog/(.*)$ /services/$1 [L] internally rewrites the URI, so that the browser doesn't know it's happening, this happens entirely on the server's end. If you want the browser to actually load a different URL, you need to use the R flag like you are in your www redirect, though it's only redirecting requests to root. If you want it to redirect everything to include the "www", you want something like this:

RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

Then to redirect "blog" to "services", just add the R flag (or R=301 if you want the redirect to be permanent).

RewriteRule ^blog/(.*)$ /services/$1 [L,R]

And, if for whatever reason your content isn't actually at /blog/, you need to internally rewrite it back

RewriteCond %{THE_REQUEST} ^GET\ /services/
RewriteRule ^services/(.*)$ /blog/$1 [L]

But this is only if your content is really at /blog/ but you only want to make it appear that it's at /services/.

Share:
14,893
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin over 1 year

    I am trying to change the url that is displayed in the address bar from mysite.com/blog/wedding-hair/ to mysite.com/services/wedding-hair/ using .htaccess.

    Using answers from:

    I added to the .htaccess file. Here is the .htaccess file, I added the last rewrite rule:

    Options -Indexes
    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^mysite.com$
    RewriteRule ^/?$ "http\:\/\/www\.mysite\.com" [R=301]
    RewriteRule ^blog/(.*)$ /services/$1 [L]
    

    the non-www redirect works but not the blog-services rewrite. I thought maybe I had the directory names reversed but changing them around doesn't work either. I have tried adding and removing /'s around the directory names in all of the different combinations. I tried adding

    RewriteCond %{THE_REQUEST} ^GET\ /blog/
    

    before my RewriteRule. Nothing I Have tried has worked, the displayed url remains mysite.com/blog/wedding-hair/

    I am sure this is pretty straight forward for someone but I am unable to get this correct. Any help would be appreciated.

    When I was working on this yesterday I didn't think about the fact that the blog directory is a WordPress install. Here is the .htaccess file that is in the blog directory:

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

    I have tried adding my RewriteRule in this file but still no joy.