phcm
phcm

Reputation: 83

Remove two subdirectories from url with mod_rewrite

I'm trying to get rid of some subdirectories on my website. Currently when I need to access user settings I use this username.mywebsite.com/public/user/settings.php and I want it to look like username.mywebsite.com/settings.php. In my root directory a have a htaccess file with the following:

RewriteCond %{REQUEST_URI} !^/public/user

RewriteRule ^/(.*)$ /public/user/$1

and it's not working. Also, do I have to modify the html href like this <a href="/settings.php">? Thank you

Upvotes: 2

Views: 64

Answers (1)

Jon Lin
Jon Lin

Reputation: 143946

You need to get rid of the leading / in your regex pattern. The slash is stripped off when URI is sent through rules in an htaccess file. Also, you should instead check to see if the destination exists before rewriting into the /public/user/ directory:

RewriteCond %{REQUEST_URI} !^/public/user
RewriteCond %{DOCUMENT_ROOT}/public/user%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}/public/user%{REQUEST_URI} -d
RewriteRule ^(.*)$ /public/user/$1 [L]

Also, do I have to modify the html href like this <a href="/settings.php">?

Yes, the rule only works in one direction, regex pattern to target. Never the other way around. So you need to make sure your content has the URLs that you want to use.

Upvotes: 1

Related Questions