Rewrites and Redirection
Updated on 30 Mar 2020
Redirect to a new directory
One of my practice applications is set up like this in Apache.
alias /yii1-docs "/var/www/yii/yii1/docs"
<Directory /var/www/yii/yii1/docs>
#Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
I want to navigate to http://yii/yii1-docs
, and my documentation page will just open. It has done that in the below screen shot, however the URL displayed in the address bar is different to what I typed in. Infact it automatically went there.
So how did I do it? Easy, I used a redirectMatch.
alias /yii1-docs "/var/www/yii/yii/docs"
<Directory /var/www/yii/yii1/docs>
# this is not so good because although it displays, the css, javascript is missing
# plus the api in the address bar is missing...
# DirectoryIndex api/index.html
#Options Indexes FollowSymLinks
AllowOverride All
Require all granted
# this works perfectly. Redirects as expected
RedirectMatch ^/yii1-docs/$ /yii1-docs/api/
</Directory>
Redirect to a new file
The previous example was great at redirecting to a new directory; this works if you’re using a framework or DirectoryIndex and you have an index.html file. But what if you need to specify a file? That can be done too.
RedirectMatch ^/yii1-test/$ "/yii1-test/tests/_output/report.html"
Redirect to https
You can also redirect to https if you want to.
alias /yii1 "/var/www/yii/yii1/web"
<Directory /var/www/yii/yii1/web>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
#this redirects to https
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
</Directory>
For more information on SSL and setting up Apache for SSL connections, make sure you check out my SSL tutorials.