Score:1

how to redirect a web page based on domain name using .htaccess

bi flag

At a site serving multiple domains (example.com, example.org, etc.), we would like to redirect a page depending on the domain:

https://www.example.com/page1 => https://www.example.com/page2
https://www.example.org/page1 => https://www.example.org/page3

using .htaccess, but the following:

Redirect "/page1" "https://www.example.com/page2"

will be applied to both domains. How can this be done?

Score:1
in flag

The recommendation from the Apache project is:

In general, you should only use .htaccess files when you don't have access to the main server configuration file. [In other words: your site is on shared hosting and you don't have administrator level access to the main apache httpd configuration] ... a common misconception is that user authentication and mod_rewrite directives must go in .htaccess files.

Because there is a performance penalty for using the .htaccess mechanism.

So preferably you should simply adjust your httpd.conf (or the includes used to set up your sites) to have separate stanza's for each of your domains and make the necessary redirects there:

<VirtualHost *:443>
    DocumentRoot "/www/example"
    ServerName www.example.com

    # Other directives here

    Redirect "/page1" "https://www.example.com/page2"
</VirtualHost>

<VirtualHost *:443>
    DocumentRoot "/www/example"
    ServerName www.example.org

    # Other directives here

    Redirect "/page1" "https://www.example.org/page3"
</VirtualHost>

When you're on shared hosting and absolutely must use an .htaccess file; your question is actually off-topic for ServerFault, but the approach would be to make different conditional redirects, based on the HTTP Host: header the client uses.

You can alternatively accomplish this using the <If> directive:

<If "%{HTTP_HOST} == 'www.example.com'">
    Redirect "/page1" "https://www.example.com/page2"
</If>
<If "%{HTTP_HOST} == 'www.example.org'">
    Redirect "/page1" "https://www.example.org/page3"
</If>

Or with mod_rewrite rules :

RewriteCond "%{HTTP_HOST}"   "^www\.example\.com" [NC]
RewriteRule "^/page1"        "https://www.example.com/page2" [R]

RewriteCond "%{HTTP_HOST}"   "^www\.example\.org" [NC]
RewriteRule "^/page1"        "https://www.example.org/page3" [R]
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.