Home » Php » php – URL rewrite to add a directory at start of url

php – URL rewrite to add a directory at start of url

Posted by: admin July 12, 2020 Leave a comment

Questions:

On my website, all images/stylesheets are in the /CMS/… directory. Recently, our website shifted to new server at a temporary url where they referenced like /newdirectory/CMS/…

How can we append /newdirectory/ to all /CMS/ calls?

How to&Answers:

Inside the .htaccess file

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/newdirectory/CMS/
RewriteRule ^(.*)$ /newdirectory/CMS/$1

This will perform a rewrite, so accessing http://www.server.com/CMS/index.html will actually serve the content of http://www.server.com/newdirectory/CMS/index.html

Note: This solution assumes that the CMS is the only thing being served for this domain.

If this domain is serving more than the CMS (and only the CMS should be redirected), then the following may be better:

RewriteEngine On
RewriteCond %{REQUEST_URI} ^/CMS/
RewriteRule ^(.*)$ /newdirectory/$1

Answer:

You don’t need a RewriteRule (or mod_rewrite) for this. You can use a simple RedirectMatch:

RedirectMatch ^/CMS/(.*) http://tempserver.com/newdirectory/CMS/$1

Answer:

I’d suggest using mod_rewrite, which most apache/linux servers have. Create a file called .htaccess in the docroot of your site with the contents:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^/CMS/(.*)$      /newdirectory/CMS/$1    [QSA]
</IfModule>

This method will make it transparent to the end user and no impact on current pagerank, SEO, etc value and all inbound links will be maintained.