URL redirecting to avoid access to subdirectories

New to mod_rewrite? This is a good place to start.

URL redirecting to avoid access to subdirectories

Postby bhushan » Wed Apr 15, 2009 10:30 pm

In my project I want to restrict access to subdirectories on the server and want to give access to only the root location.

So lets say user hits http://localhost/ he will be shown the index page but if he types http://localhost/somdir he should not be taken to this directory/location and instead redirected to http://localhost loading the index page.

Environment is as follows:

OS: Linux
Server: Apache
Backend is developed in PHP.

To achieve this I am using the .htaccess file with following rules

Options +FollowSymLinks
RewriteEngine on
RewriteBase /

RewriteCond %{HTTP_HOST} !^localhost/
RewriteRule ^(.*)$ http://localhost/ [L,R=301]

Here the redirection happens properly but the rewrite condition (RewriteCond) which is put to avoid looping to http://localhost doesn’t seem to be working. The browser is throwing error.

I want to avoid doing this using httpd.conf file of Apache as the application will be distributed and making changes to httpd.conf will not the advisable/feasible.

Any help in this context or suggestions for alternatives will be highly appreciated.

Thanks in advance.
bhushan
 
Posts: 2
Joined: Wed Apr 15, 2009 10:25 pm

Postby richardk » Thu Apr 16, 2009 8:53 am

%{HTTP_HOST} is the domain name (in this case localhost) only.
%{REQUEST_URI} contains the bit after the domain name (/somedir).
%{QUERY_STRING} contains the query string (a=b&c=d).

What you want to do is only match URLs that have something after the first slash, you can do this with . (a character) (or .+ (one or more characters)) instead of .* (zero or more characters) in the RewriteRule.
Code: Select all
Options +FollowSymLinks

RewriteEngine On

RewriteRule . http://localhost/ [R=301,L]
richardk
 
Posts: 8800
Joined: Wed Dec 21, 2005 7:50 am

Postby bhushan » Mon Feb 15, 2010 10:01 pm

richardk wrote:%{HTTP_HOST} is the domain name (in this case localhost) only.
%{REQUEST_URI} contains the bit after the domain name (/somedir).
%{QUERY_STRING} contains the query string (a=b&c=d).

What you want to do is only match URLs that have something after the first slash, you can do this with . (a character) (or .+ (one or more characters)) instead of .* (zero or more characters) in the RewriteRule.
Code: Select all
Options +FollowSymLinks

RewriteEngine On

RewriteRule . http://localhost/ [R=301,L]


Hi.

Thanks a lot for the solution. It helped me in solving my problem.
Thanks again and sorry for late reply. Cudn't help it due to some reasons.
bhushan
 
Posts: 2
Joined: Wed Apr 15, 2009 10:25 pm


Return to Beginner's Corner

Who is online

Users browsing this forum: No registered users and 10 guests

cron