user1527723
user1527723

Reputation: 33

Shorten URLs with mod_rewrite

I am currently trying to make a URL shortener feature for one of my projects; what I want to do if a user visits the site with a URL that does not contain any slashes (for directories) or file extensions, it should redirect to a PHP script that will serve up the correct file. For example:

http://example.com/A123 would be rewritten as http://example.com/view.php?id=A123

but http://example.com/A123/ would not be rewritten, and http://example.com/A123.png would not be rewritten either. I have been messing with mod_rewrite for a few hours now and for the life of me I cannot get this to work...

Upvotes: 1

Views: 3583

Answers (2)

Jerry
Jerry

Reputation: 76

With no way to identify the URI that needs to be shortened you need to exclude all other possibilities. This will likely require you to build a lengthy list of exclusions. Below is a starting point. Each of these conditions verifies the requesting URI does NOT match (signified by the !). When it doesn't match all conditions the rule is run.

RewriteCond %{REQUEST_URI} !^/view.php
RewriteCond %{REQUEST_URI} !.html$
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^/(.*)$ http://example.com/view.php?id=$1 [QSA]

The above also requires you (as you have requested) to break a standard practice rule, which is to handle directory requests without a trailing slash. You are likely to come across other issues, as the rules above break your Apache server side directory rules.

Rethinking the logic. If you had some way to identify the URL that is to be shortened it would be much easier. For example 's', http://example.com/s/A123.

RewriteCond %{REQUEST_URI} ^/s/
RewriteRule ^/s/(.*)$ http://example.com/view.php?id=$1 [QSA]

Upvotes: 2

Zach Lysobey
Zach Lysobey

Reputation: 15724

I'm definitely no guru at this, but its similar to what I'm trying to accomplish (see my yet unanswered question)

However, if I understand correctly, this (untested) RewriteRule may work:

RewriteRule ^([^\.\/]*)$ view.php?id=$1 [L]

The magic part is the [^\.\/]* which says: 1 or more (*) instances of a charactor ([]) which is not ([^ ]) a period or a slash (\ escapes these charactors).

Like I said, I haven't tested this, nor am I an expert, but perhaps this will help.

Upvotes: 0

Related Questions