简体   繁体   中英

How to Rewrite (HTACCESS) Domain & Directory to URL Variables?

I wrote a URL shortener that supports multiple Internet domains. Now, to use it, I need .htaccess to rewrite inbound requests, so the domain and directory of the shortened URL become URL variables. For example, if I have two domains dedicated to short URLs, BRIEF.LY and SHORT.LY, here's what .htaccess should do:

http://brief.ly/B17r   =>   http://example.com/?DID=1&UID=B17r
http://short.ly/aX7f   =>   http://example.com/?DID=2&UID=aX7f

...where DID represents the database index of the domain and UID represents the index of the shortened URL. With those two values, EXAMPLE.COM can query the database for the respective target URL and forward the visitor accordingly.

I believe I can accomplish this in two REWRITES - one for each domain. [I don't anticipate adding any more domains, so the "DID=" part of it can be static.]

Unfortunately, my RegEx skills are dismal and an hour of online searches has only turned up rewrites performing the OPPOSITE function.

Any help is greatly appreciated.

Well, it took me a while, but this appears to be working:

# Translate BRIEF.LY Short URLs
RewriteCond %{HTTP_HOST} ^(www\.)?brief\.ly$ [NC]
RewriteCond %{REQUEST_URI} ^/(.+)$
RewriteRule .? http://example.com/shorturl/?DID=1&UID=%2 [QSA,L]

# Translate SHORT.LY Short URLs
RewriteCond %{HTTP_HOST} ^(www\.)?short\.ly$ [NC]
RewriteCond %{REQUEST_URI} ^/(.+)$
RewriteRule .? http://example.com/shorturl/?DID=2&UID=%2 [QSA,L]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM