AlexMorley-Finch
AlexMorley-Finch

Reputation: 6955

.htaccess redirect based on multiple conditions

Im trying to configure a .htaccess RewriteRule and i'm struggling.

I have a domain www.domain.com

I'm trying to add these conditions.

I'm working on www.domain.com/.htaccess

if URL is www.domain.com with no path to file, redirect to www.domain.co.uk

if URL is www.domain.com AND has a path to file, no rewrite, allow.

if URL is www.domain.com AND has a path to file AND file doesnt exist, return 404

if URL points to a directory, return access forbidden

They are my requirments.

I've tried multiple things. Heres my .htaccess

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.domain.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.co.uk/$1 [R=301,L]

This code satisfies the first constraint.

However i have no idea how to check if a path exists, if the path is valid, or if its a directory.

A perfect answer would be code satisfying all the constraints and explainatoin how it works.

I've read the mod_rewrite documentation more times than I care to admit :'(

Upvotes: 0

Views: 1932

Answers (1)

poncha
poncha

Reputation: 7866

# Make sure / redirected to other domain
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC]
RewriteRule ^/$ http://www.domain.co.uk [R=301,L]

# Make sure directory listings are forbidden
Options -Indexes

Note that you can use RedirectMatch, which is actually preferred over rewriting in this case

and there is no need to handle files at all in your case - if the URI is not /, then the rules do not apply and regular file handling will be performed (404 error if not found, etc... )

Upvotes: 1

Related Questions