Shorten URL with Regex

Shorten URL with Regex - .htaccess files are extremely useful in many cases for users who either do not have root permissions or for users who simply aren't comfortable in making changes in their web server's configuration file. Trying to debug .htaccess not working isn't always the easiest thing to do, however, hopefully by checking the discuss below mentioned about php, htaccess, url, , .htaccess common problems as well as the troubleshooting tips, you'll have a better grasp on what you may have to modify to get your .htaccess file running smoothly.Problem :


Here's an example URL to a user profile on my site: http://127.0.0.1:8080/overview/showuserprofile/user



I want it to be:



http://127.0.0.1:8080/user



This is what I have for rewrite rules:



  Options -MultiViews
RewriteEngine On
RewriteBase /php-login/
RewriteCond %REQUEST_FILENAME !-d
RewriteCond %REQUEST_FILENAME !-f
RewriteCond %REQUEST_FILENAME !-l

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]


That gets rid of the .php at the end.



I've also tried adding



RewriteRule ^(.+)$ index.php?url=/overview/showuserprofile/$1 [QSA,L]



But the URL would change and not any of the pages.



Any ideas?


Solution :

You will need to figure out how to differentiate user pages from other pages. Your rewrite expression ^(.+)$ matches all the pages on the site except for the home page. You will need to limit this so that it doesn't match other pages including index.php.



One way of doing so would be to only allow user pages to use lower case letter with no punctuation. Then it wouldn't match index.php due to the period. The rewrite rule for that would be:



RewriteRule ^([a-z]+)$ index.php?url=/overview/showuserprofile/$1 [QSA,L]


Another way to do it would be to check that there isn't a real file with that name as a rewrite condition using the instructions here: http://www.harecoded.com/apache-rewritecond-f-check-file-exists-solution-2246468


Additionally, if you would like to do some further testing, give the htaccess tester tool a try. It allows you to specify a certain URL as well as the rules you would like to include and then shows which rules were tested, which ones met the criteria, and which ones were executed.

Comments

Popular posts from this blog

Rewrite in Mediawiki, remove index.php, .htaccess

.htaccess rewrite wildcard folder paths from host

Using .htaccess to set a cookie and 301 redirect