Question

I'm trying to make a URL shortening service for my website.

So instead of:

http://www.myfullwebsitename.com/page78/this-is-a-headline/

users will be able to visit:

http://abc.de/aBxf

which needs to redirect (invisibly!) to

http://abc.de/?shorturl=aBxf

which then 301 redirects via a database lookup to

http://www.myfullwebsitename.com/page78/this-is-a-headline/

I can do the DB lookup and the 301 redirect easily. It's the invisible intermediate redirect that I'm struggling with.

I've tried a LOT of different things, but none seems to work. This is what I currently feel should work:

RewriteCond %{HTTP_HOST} ^abc.de
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^/(.+)  /?shorturl=$1

But instead of redirecting silently to

http://abc.de/?shorturl=aBxF 

it redirects "noisily" (302) to

http://abc.de/aBxF/?shorturl=aBxF 

What am I doing wrong?

Thank you!

Was it helpful?

Solution

There's a few things you can try.

I think your RewriteRule should look like this (without the forward /):

RewriteRule ^/(.+)  ?shorturl=$1 [L]

This should at the very least stop it from redirecting to http://abc.de/aBxF/.

Your original rule may work if you add:

RewriteBase /

If it were me my rules would actually look like this:

RewriteBase /
RewriteCond %{HTTP_HOST} ^abc.de$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .  /redirect.php [L]

And then in PHP I would use $_SERVER['REQUEST_URI'] to get the URL (not sure what language you're using).

The rule can look like this:

RewriteRule ^(.*)$  /redirect.php?shorturl=$1 [L]

But I would make sure to mention the script by name. Part of what may be throwing your rules off is relying on Apache finding your index file after a rewrite.

The way Apache's rewrite rules work is as soon as the URL is rewritten, it actually will re-run the rules until no other rules will be found. The [L] flag for "last" says "stop here" - but it still starts over from the top. The RewriteCond with the !-f flag says "only if the file doesn't exist".

OTHER TIPS

Use an absolute URL:

RewriteCond %{HTTP_HOST} ^abc.de
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^(.*)$ http://abc.de/?shorturl=$1 [R=301,L]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top