jmsiox
jmsiox

Reputation: 123

Rewrite rules for redirect URLs using .htaccess

I am using .htaccess to redirect URLs on my website to avoid having links like for example page1.php.

I have a subfolder engine/index.php on the root domain that i intend to use to process the redirected URL.

e.g i want the link localhost/user to rewrite to localhost/engine/index.php?view=user NOTE:The links being used i.e /user is not a file or folder existing on the domain

Upvotes: 1

Views: 76

Answers (1)

Jonan
Jonan

Reputation: 2536

Use this:

RewriteEngine On

RewriteRule ^([a-z]+)$ engine/index.php?view=$1 [NC,L,QSA]

Put this in your .htaccess file directly in your www/ directory.
([a-z]+) will match a group of letters (also capitals since the NC flag is used), but if something else than a letter is behind localhost/ the url won't be rewritten. If there are only letters behind localhost, the url will rewritten to engine/index.php?view=$1

The L flag indicates that this is the last RewriteRule, and the QSA flag appends the old querystring to the new one. For example: localhost/user?var=val will redirect to localhost/engine/index.php?view=user&var=val.

But, if the user goes to localhost/user?view=somethingelse, it will be rewritten to localhost/engine/index.php?view=user&view=somethingelse which means that if you do $_GET['view'] in engine.php, it will return "somethingelse". To get the first view parameter from the querystring (user), use this regex in PHP:

$view = preg_replace('/view=([^&]+).*/', '$1', $_SERVER['QUERY_STRING']); //now, $view contains 'user'

Upvotes: 1

Related Questions