Wondering Coder
Wondering Coder

Reputation: 1702

Conditional htaccess

I just want some help with my .htaccess configuration. Before I have this problem where I need to redirect the page to a specific url. Like if the user type http://mydomain/test it will be redirected to http://mydomain/app/r/test. I achieved the redirection using .htaccess. The code is below

RewriteEngine on
RewriteRule (.*) http://mydomain/app/r/$1 [R=301,L]

But I have this new specification. As follows:

If user visit http://mydomain/ or http://domain/index.php, he will be redirected to http://mydomain/mymanager

If user visit http://mydomain/{any_segment}, he will be redirected to http://mydomain/app/r/{any_segment}

Here is my current htaccess. Basically in the url, any characters will be redirected to /app/r/{} except index.php. But what about the http://domain/? How can I achieve this.

RewriteEngine on

RewriteCond %{HTTP_HOST} ^mydomain$ [OR]
RewriteCond %{HTTP_HOST} ^www.mydomain$
RewriteCond %{REQUEST_URI} !^/index.php
RewriteRule ^(.*)$ http://mydomain/app/r/$1 [R=301,L]

I've been playing around my htaccess and any pointers will be of great help to me.

Upvotes: 0

Views: 74

Answers (1)

Mohammed Elhag
Mohammed Elhag

Reputation: 4302

These are your rules :

RewriteEngine on
RewriteCond %{HTTP_HOST} ^mydomain$ [OR]
RewriteCond %{HTTP_HOST} ^www.mydomain$
RewriteCond %{REQUEST_URI} !^/index.php
RewriteRule ^(.*)$ http://mydomain/app/r/$1 [R=301,L]

It looks like , any request should redirect to /app/r/ except A URI start with /index.php but still not doing that , in normal cases , so you should exclude the target directory from being redirect again and again by this rule RewriteRule ^(.*)$ http://mydomain/app/r/$1 [R=301,L] , ^(.*)$ means any URI start with any thing and the server will look, if there is a condition , and actually there is only one condition to exclude index.php, otherwise redirect .

So , you should exclude this target directory along with index.php like this :

RewriteCond %{REQUEST_URI} !^(/index\.php|/app/r/)

But still you want to match a request that target HOST only so,you should add that as well :

RewriteCond %{REQUEST_URI} !^(/index\.php|/app/r/|/?$)

Then you could match host with www or non-www like this :

RewriteCond %{HTTP_HOST} ^(www\.)?mydomain$ 

Your rules should look like this :

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?mydomain$
RewriteCond %{REQUEST_URI} !^(/index\.php|/app/r/|/?$)
RewriteRule ^(.*)$ http://mydomain/app/r/$1 [R=301,L]

Also you could summarize that more by utilizing %{REQUEST_URI} like this :

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.)?mydomain$
RewriteRule !^(index\.php|app/r/|/?$) http://mydomain/app/r%{REQUEST_URI} [R=301,L]

NOTE: Clear browser cache then test

Upvotes: 1

Related Questions