Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rewrite a subdomain to a variable in a URL? [duplicate]

Possible Duplicate:
Apache rewrite based on subdomain

Is it possible to rewrite a URL like this?

www.foo.website.com/some-page

to

www.website.com/some-page?var=foo

I'm asking about a rewrite (I think that's what it's called) and not a redirect. i.e. I want the first URL to stay in the address bar, but for the server to "get" the second URL.

I've never understood how to do URL rewrites and so far my pathetic attempts to get this working have failed miserably :-)

I should add that this .htaccess file is also being used by WordPress and has the following code:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /~kbj/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /~kbj/index.php [L]
</IfModule>

Any help or advice would be very much appreciated!

like image 261
Nate Avatar asked Oct 08 '22 10:10

Nate


2 Answers

What I'll explain is for multilanguage websites, but you can very easily apply this to what you're asking: rename "LANGUAGE" to "var" (smile).

Here's what you may want to do, to be able to handle in the future many sub languages. Check your host: if it contains a "known language", add it in a global variable (= environment variable from Apache's point of view) then at the end, if the "language" variable is not set, set is as the default language. And finally, add it as a parameter.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^www\.([^.]+)\.website\.com$
    RewriteRule ^(.*)$ "http://www.website.com/$1?var=%1" [P]

    RewriteCond %{HTTP_HOST} ^(www\.)?(us|fr|pt)\.mydomain\.com$
    # Create an environment variable to remember the language:
    RewriteRule (.*) - [QSA,E=LANGUAGE:%2]
    # Now check if the LANGUAGE is empty (= doesn't exist)
    RewriteCond %{ENV:LANGUAGE} ^$
    # If so, create the default language (=es):
    RewriteRule (.*) - [QSA,E=LANGUAGE:es]
    # Add the language to the URI (without modifying it):
    RewriteCond (.*) $1?language={ENV:LANGUAGE} [QSA]

</IfModule>

(note: please, please... use proper indentation).

like image 77
Olivier Pons Avatar answered Oct 12 '22 00:10

Olivier Pons


RewriteCond %{HTTP_HOST} ^www\.([^.]+)\.website\.com$
RewriteRule ^(.*)$ "http://www.website.com/$1?var=%1" [P]

Use the P flag to proxy the request.

http://httpd.apache.org/docs/current/rewrite/flags.html#flag_p

like image 42
Manish Avatar answered Oct 12 '22 00:10

Manish