Alex Sarnowski
Alex Sarnowski

Reputation: 739

Rewrite URL using .htaccess to shorten link

I am looking to be able to take the url

www.mydomain.com/profile.php?user=THEUSERNAME

and turn it into

www.mydomain.com/THEUSERNAME

Almost like Twitter.

I also want to be able to have it where i can go to

www.mydomain.com/THEUSERNAME

and it will go to the user's page, without changing the URL back to the long URL. I don't know how this is done and I also don't whether it will require .htaccess, PHP or possibly both. Please help.


SOLOUTION FOUND


Inside your .htaccess file:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/\.]+)/?$ profile.php?user=$1 [L]

Also you are going to need to give the absolute URL to all of your CSS and JS files. For example, instead of having src="css/main.css" , you have to put src="http://yourdomain.com/css/main.css". The reason being is because if your url has a backslash (i.e yourdomain.com/USERNAME/) than it will think it is in the next directory and it will cause conflict. Absolute solves the CSS and JS problem.

In the <head> of profile.php:

NOT THIS:

   <link href="css/allpage.css" rel="stylesheet" type="text/css" />

THIS:

   <link href="http://yourdomain.com/css/allpage.css" rel="stylesheet" type="text/css" />

Upvotes: 2

Views: 3315

Answers (2)

Luis
Luis

Reputation: 1097

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ /profile.php?name=$1 [L]

That would work, http://yoursite.com/username (with or without trailing slash) will rewrite to http://yoursite.com/profile.php?user=username

Also you must use / based files (for <script> and <link>) or full URLs, if not you may get some 404 errors. I also suggest you to add a CDN and you can push that links vía CDN, one very good is maxCDN - 40USD the first TERABYTE!.

Good luck!

Upvotes: 2

rodneyrehm
rodneyrehm

Reputation: 13557

try this

RewriteEngine on
# we're working the document root
RewriteBase /
# make sure requested item is not a file
RewriteCond %{REQUEST_FILENAME} !-f
# re-route everything that may be a username slug to the profile
RewriteRule ^([^/]+)/?$ /profile.php?name=$1 [L]

Upvotes: 1

Related Questions