Apache redirect / rewrite

Howto redirect links or rewrite addresses …

mod_rewrite

Redirect everything to a “maintenance” message

RewriteEngine on
RewriteRule !wartung.htm$ http://www.foo.tld/wartung.htm [R,L]

redirects everything but wartung.htm

RewriteCond /maintenance.html -f
RewriteCond !maintenance.html
RewriteRule ^.*$ /maintenance.html [L]

if maintenance.html exists, everything is redirected to this page.

Redirect everything on the same host to Port 443 (SSL)

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

redirect

Simple redirect in .htaccess

Redirect / http://www.foo.tld/

or

Redirect 301  / http://www.foo.tld/

Redirect everything to a single URL (.htaccess)

RedirectMatch ^.*$ http://www.domain.tld
Redirect / http://www.domain.tld

php

If PHP ist installed you can use as well:

<?php
  header("Location: http://psc.tobanet.de");
?>

or to give a specific http_response_code other than 302:

<?php
  header("Location: http://psc.tobanet.de", true, 301);
?>

Put this in your index.php and your visitor will be redirected.

force ssl with basic auth

To force a https (ssl) connection for a directory with basic auth the following hack works if you have to workaround a loadbalancer doing the ssl connection:

Assumption:

  • SOME_HEADER_SSL = 0 if http
  • SOME_HEADER_SSL = 1 if https
.htaccess
RewriteEngine On
SetEnvIf SOME_HEADER_SSL ^1$ let_me_in
 
# redirect to https:
ErrorDocument 403 /403.php
 
RewriteCond %{HTTP:SOME_HEADER_SSL} ^0$
RewriteRule (.*) https://%{SERVER_NAME}%{REQUEST_URI}  [R=301,L]
 
order Deny,Allow
Deny from all
allow from env=let_me_in
 
AuthName "Secure dir"
AuthType Basic
AuthUserFile /htpasswd
AuthGroupFile /htgroup
 
<Limit GET>
require group allin
</Limit>
403.php
<?php
header('Location: https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
?>
apache/redirect.txt · Last modified: 2011/03/21 11:05 by tb
CC Attribution-Noncommercial-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0