Forum Moderators: phranque

Message Too Old, No Replies

.htaccess RewriteRule

         

username

12:57 am on Sep 1, 2009 (gmt 0)

10+ Year Member Top Contributors Of The Month



Hi all, I need some assistance with an area of my .htaccess file if possible. My current code:

RewriteEngine on
RewriteRule ^([^/\.]+)/?$ /users/index.php5?name=$1 [L,NC,QSA]
RewriteRule ^([^/\.]+)/([^/\.]+)/?$ /users/index.php5?name=$1&display=$2 [L,NC,QSA]

Has two variables which I GET and perform functions on using PHP. The only problem is that some of the values for the name variable have non alphanumeric characters such as the full stop or dash. These are the only two chars I allow like this, but are causing the pages which have this to load incorrectly.

The following works:

name=test&display=content

The following needs to work:

name=example.com.au&display=content
name=example.com.au-test&display=content

I just can't get the string to allow all characters properly.

Thanks in advance.

jdMorgan

1:43 am on Sep 1, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You really need to re-design your URL system, then, to eliminate the need for those characters, to encode those characters, or to exclude certain requests from each rule. Here's why:

If you change the sub-patterns above from "[^/\.]+" to "[^/]" in order to allow periods/full stops, then look what happens with your second rule:
The requested URL-path /example.com.au-test/content/
gets rewritten to /users/index.php5?name=example.com.au-test&display=content

But then, that new path matches the pattern, and so the request gets re-rewritten to
/users/index.php5?name=example.com.au-test&display=content&name=users&display=index.php5

It will continue to get rewritten again and again, each time adding another "&name=users&display=index.php5" to the query string, until the server gives up or the client times out.

The first rule is even worse, since allowing full stops/periods would cause it to rewrite requests for robots.txt, sitemap.xml, and all image, .css and .js files in your root directory to /users/index.php5?name=robots.txt (for example.)

So, lacking any knowledge of your site, the only 'quick fix' I could suggest would be something like:


RewriteEngine on
#
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ /users/index.php5?name=$1 [NC,QSA,L]
#
RewriteCond $1 !^users/
RewriteRule ^([^/]+)/([^/]+)/?$ /users/index.php5?name=$1&display=$2 [NC,QSA,L]

Note that I used a URL-path exclusion on the second rule because I could, and because it is much, much, much more efficient than checking for 'exists'. You may need to add more exclusions to the second rule if you have any additional 'real' subdirectories.

Jim