.htaccess Redirect all pages except one and another internal redirect of a certain domain

Viewed 464

I want to redirect all request of one particular domain to another, except for one page request. I hope my attempt explains what I try to do:

RewriteEngine on

Rewritecond %{HTTP_HOST} !^host\.mysite\.com
RewriteRule ^link/([^/]+)/([^/]+)/([^/]+)$          dokument_by_link.php?$1=1&document_type=$2&value=$3 [NC,L]

Rewritecond %{HTTP_HOST} !^host\.mysite\.com
RewriteCond %{REQUEST_URI} !^/link/
RewriteCond %{REQUEST_URI} !^dokument_by_link\.php
RewriteRule (.*)                                    https://www.anothersite.de/$1 [R=302,L]

#This should not apply to host.mysite.com, but I think this is already accomplished by the L-flag above
RewriteRule ^test/?$                                       test.php [L,NC]

host.mysite.com/link/ should be redirected to host.mysite.com/document_by_link.php

RewriteRule ^link/([^/]+)/([^/]+)/([^/]+)$ dokument_by_link.php?$1=1&document_type=$2&value=$3 [NC,L]

All other requests should be redirected to https://www.anothersite.de

Thank you very much!

2 Answers

This should do the trick :

RewriteEngine on

#rewrite /link to /document_by_link.php
RewriteRule ^link/?$ /document_by_link.php [L]
#redirect all other URLs to https://www.anothersite.de
RewriteRule !dokument_by_link\.php$ https://www.anothersite.de%{REQUEST_URI} [L,R]

This should work for you:

RewriteEngine On

Rewritecond %{HTTP_HOST} ^host\.mysite\.com$ [NC]
RewriteCond %{THE_REQUEST} !\s/link/ [NC]
RewriteRule ^ https://www.anothersite.de%{REQUEST_URI} [R=302,L,NE]

Rewritecond %{HTTP_HOST} ^host\.mysite\.com$ [NC]
RewriteRule ^link/([^/]+)/([^/]+)/([^/]+)$ dokument_by_link.php?$1=1&document_type=$2&value=$3 [NC,L,QSA]

RewriteRule ^test/?$ test.php [L,NC]

Using THE_REQUEST instead of REQUEST_URI here as REQUEST_URI may change to a rewritten URI whereas THE_REQUEST remains same for the scope of a web request.

THE_REQUEST variable represents original request received by Apache from your browser and it doesn't get overwritten after execution of other rewrite directives. Example value of this variable is GET /index.php?id=123 HTTP/1.1

Related