Simple 301 redirect with htaccess

2019-09-14 23:03发布

I want to redirect a URL from a page that is no longer active. The URL https://tchibo.academyofsports.promo/ as well as all subpages should be redirected to the URL http://www.academyofsports.de/. This is what I have so far (.htaccess):

#Redirects

RewriteEngine On
RewriteRule https://tchibo.academyofsports.promo/ http://www.academyofsports.de/ [L,R=301]

Unfortunately it does not work in this way. What am I doing wrong?

1条回答
Explosion°爆炸
2楼-- · 2019-09-14 23:43

This one probably is what you are looking for:

RewriteEngine On
RewriteCondition %{HTTP_HOST} ^tchibo\.academyofsports\.promo$ [NC]
RewriteRule ^/?(.*)$ http://www.academyofsports.de/$1 [L,R=301]

Reason is that a RewriteRule only operates on the path component of the requested URL, it cannot see the host name. The above rule should work likewise in the http servers host configuration and dynamic configuration files.

If you are not interested in the path that got requested originally but want to redirect everyone to the entry point, then you can simplify the above to:

RewriteEngine On
RewriteCondition %{HTTP_HOST} ^tchibo\.academyofsports\.promo$ [NC]
RewriteRule ^ http://www.academyofsports.de/ [L,R=301]

And a general hint: you should always prefer to place such rules inside the http servers (virtual) host configuration instead of using dynamic configuration files (.htaccess style files). Those files are notoriously error prone, hard to debug and they really slow down the server. They are only provided as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).


Reacting to your comment below I want to add this:

To implement specific mappings you can also add exception rules:

RewriteEngine On

RewriteCondition %{HTTP_HOST} ^tchibo\.academyofsports\.promo$ [NC]
RewriteRule ^/?agb\.html$ http://www.academyofsports.de/Datenschutz [L,R=301]

RewriteCondition %{HTTP_HOST} ^tchibo\.academyofsports\.promo$ [NC]
RewriteRule ^/?(.*)$ http://www.academyofsports.de/$1 [L,R=301]

The issue is that you have to repeat the condition for each single rule due to the internal logic of the rewrite module. There are one or two crude hacks to get around this, but things get hard to maintain very fast that way. If you need to specify multiple such exception rules a RewriteMap is the way to go.

查看更多
登录 后发表回答