Home > database >  Is there any possibility to have htaccess 301 Redirects with absolute path?
Is there any possibility to have htaccess 301 Redirects with absolute path?

Time:03-28

i wondering if there is any way to have redirects like

Redirect 301 https://www.mypage.com/test https://www.mypage.com

as background: i need this because i have a website with 3 different languages and each language runs on a different domain. If I'm doing /test with an related path it will affect each of my domains but i only want have the redirect for one specific domain.

i was trying it as i showed in my example but it was then no longer working.
i also was trying it with RewriteCond for my apache directives but it was also not working with absolute paths

CodePudding user response:

Redirect 301 https://www.mypage.com/test https://www.mypage.com

The mod_alias Redirect directive matches against the URL-path only.

You need to use mod_rewrite to check the Host header using the HTTP_HOST server variable in a condition (RewriteCond directive). For example:

RewriteEngine On

RewriteCond %{HTTP_HOST} =www.example.com [NC]
RewriteRule ^test$ https://www.example.com/ [R=302,L]

The RewriteRule pattern (first argument) is a regex that matches against the URL-path only (similar to the Redirect directive, except there is no slash prefix when used in .htaccess).

The above will issue 302 (temporary) redirect from https://www.example.com/test (HTTP or HTTPS) to https://www.example.com/.

If you are redirecting to the same hostname then you don't necessarily need to include the scheme hostname in the substitution string (2nd argument to the RewriteRule directive). For example, the following is the same as above*1:

RewriteCond %{HTTP_HOST} =www.example.com [NC]
RewriteRule ^test$ / [R=302,L]

(*1 Unless you have UseCanonicalName On set in the server config and ServerName is set to something other than the requested hostname.)

Note that the above matches www.example.com exactly (the = prefix operator on the CondPattern makes it a lexicographic string comparison).

To match example.com or www.example.com (with an optional trailing dot, ie. FQDN) then use a regex instead. For example:

RewriteCond %{HTTP_HOST} ^(?:www\.)?(example\.com) [NC]
RewriteRule ^test$ https://www.%1/foo [R=302,L]

Where %1 is a backreference to the first captured group in the preceding CondPattern (ie. example.com). So, the above will redirect https://example.com (or www.example.com) and redirect to https://www.example.com/foo (always www).

Reference:

CodePudding user response:

In this case you need write a RewriteCond, as follow example:

RewriteEngine On
RewriteCond %{REQUEST_URI} /test1
RewriteRule (.*) https://example.com/test1/$1 [R=301,L]
RewriteCond %{REQUEST_URI} /test2
RewriteRule (.*) https://example.com/test2/$1 [R=301,L]

  • Related