P
P
Pavel2018-07-05 05:32:48
htaccess
Pavel, 2018-07-05 05:32:48

How to implement separate redirects in htaccess?

Faced with the task: you need to make a 301 redirect if the site does not start with www in any case. If the site is not requesting a search robot, then a 302 redirect to the mirror should occur. If a search robot requests, then control should be transferred to the current domain. Do not even ask why this is, but they set such a task. Now I have implemented half of the task in .haccess, and the other by writing a plugin for the CMS.
But the method is not universal and I try to do it like this:

RewriteEngine On
RewriteBase /

# Редирект если не робот и начинается с www
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteCond %{HTTP_USER_AGENT} !(googlebot|yandexbot|msnbot) [NC]
RewriteRule ^(.*)$ http://www.site2.com/$1 [L,R=302]

# Редирект если не начинается с www
RewriteCond %{HTTP_HOST} ^([^www].*)$ [NC]
RewriteRule ^(.*)$ http://www.%1/$1 [L,R=301]

# Запуск сайта на текущем домене
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

But it turns out that after the second passage of the .htaccess file, if the domain is without www, there is still a 302 redirect to the mirror. And I don't know how to solve this problem.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Viktor Taran, 2018-07-05
@shambler81

RewriteEngine On
RewriteBase /

# Редирект если не начинается с www
RewriteCond %{HTTP_HOST} !^www\.(.*) [NC]
RewriteRule ^(.*)$ http://www.%1/$1 [L,R=301]

# Редирект если не робот и начинается с www
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteCond %{HTTP_USER_AGENT} !(googlebot|yandexbot|msnbot) [NC]
RewriteRule ^(.*)$ http://www.site2.com/$1 [L,R=302]

# Запуск сайта на текущем домене
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

swap millet and that's it, in this case the bot will be a special case of a redirect to www, and in the second pass the urls will not change and therefore the rules will apply.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question