Remove "/php/" subdirectory from URL with .htaccess

Viewed 81

I've been trying to achieve the following rewrite/redirect on a website I'm building but I'm struggling and can't find the right answer online.

I want to rewrite

http://www.example.com/php/someFile.php

To:

example.com/someFile

I have managed to achieve most of the desired result with the following code in my .htaccess root file but I need help with removing the php subdirectory:

RewriteEngine on

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

# redirect /file.php to /file
RewriteCond %{THE_REQUEST} \s/([^.]+)\.php [NC]
RewriteRule ^ /%1 [NE,L,R]

# internally map /file to /file.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)/?$ /$1.php  [L]

Any help would be hugely appreciated.

2 Answers

Have it this way in your site root .htaccess:

RewriteEngine on

# remove www from url
RewriteCond %{HTTP_HOST} ^www\.(example\.com)$ [NC]
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

# redirect /php/file.php to /file
RewriteCond %{THE_REQUEST} \s/+(?:php/)?([^.]+)\.php [NC]
RewriteRule ^ /%1 [NE,L,R=301]

# internally map /file to /php/file.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/php/$1.php -f
RewriteRule ^(.+?)/?$ php/$1.php [L]

Make sure to test after clearing your browser cache.

With your shown samples, could you please try following. Please make sure to clear your browser cache before testing your URLs.

RewriteEngine on

# remove www from url
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^ http://example.com%{REQUEST_URI} [L,R=301,NE]

# redirect /file.php to /file
RewriteCond %{THE_REQUEST} \s/php/file\.php\s [NC]
RewriteRule ^ file [R=301]
RewriteRule ^ php/file.php [L]
Related