Ahmad Sami
Ahmad Sami

Reputation: 327

.htaccess remove .php and add url parameter

I have this URL http://localhost/signUp.php?url={somevalue} I want to convert it to be like this:

http://localhost/signUp/{somevalue}

how can I do this to all pages not just signUp.php using .htaccess?

I already found out how to remove .php but I didn't know how to add a parameter.

#Remove .php from url
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [NC,L] 

Upvotes: 1

Views: 444

Answers (1)

MrWhite
MrWhite

Reputation: 45914

Unless you have other requirements, you don't need to "remove" .php as a separate rule. You have /signUp/{somevalue} that must rewrite to /signUp.php?url={somevalue}.

This can be achieved with a rule like this:

Options -MultiViews

RewriteEngine On

RewriteRule ^(signUp)/([^/.])+$ $1.php?url=$2 [L]

Providing you restrict somevalue to not contain dots or slashes, there's no need to check that the request does not map to a file. And this is unlikely to map to a directory unless /signUp also exists as a directory.

somevalue must contain 1 or more characters. If you have further restrictions then this should be included in the regex.


UPDATE:

Thanks but this works only on signup, how i can make it work on all pages?

Assuming "all pages" consists of single path segments from the document root of 4 or more characters, containing just the characters a-z, A-Z, 0-9, _ (underscore) and - (hyphen) then change the above RewriteRule like the following:

RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^([\w-]{4,})/([^/.])+$ $1.php?url=$2 [L]

This does check that the corresponding .php file exists before rewriting the request, although that may not be strictly necessary if you have no other directives.

Upvotes: 1

Related Questions