James Yeomans
James Yeomans

Reputation: 31

apache rewrite not working as expected

i am trying to get it so that it rewrite the url into variables for php,

so far, i have:

RewriteEngine On
RewriteRule ^sub/(.*).html$ index.php?sub=$1
RewriteRule ^(.*).html$ index.php?page=$1

the /sub/ one is working perfectly fine, although the page one is not working,

sorry, beginner at the rewrite rules,

can any shed some light? i am guessing the issue is that you cant stack rewrite rules like i have...

i can not alter the directory structure in any way, so this is what i have to work with:

page.html
page2.html
sub/123.html
sub/827.html

thanks in advanced!

~Jmyeom

EDIT

adding [NC,L] at the end of the rules resolves this issue,

i.e

RewriteEngine On
RewriteRule ^sub/(.*).html$ index.php?sub=$1 [NC,L]
RewriteRule ^(.*).html$ index.php?page=$1 [NC,L]

although, now, how would i make it so that it did not rewrite on a different subfolder that is not /sub/, i.e, /src/?

Thanks again ~Jmyeom

Upvotes: 0

Views: 45

Answers (2)

Don
Don

Reputation: 184

If your URI structure is really like this:

/page.html
/page2.html
/sub/123.html
/sub/827.html

Then your Rules should be:

RewriteRule ^/sub/(.*).html$ index.php?sub=$1 [NC,L]
RewriteRule ^/(.*).html$ index.php?page=$1 [NC,L]

Otherwise I would use use this to eliminate unwanted rewrites:

RewriteRule ^/.*/sub/(.*).html$ index.php?sub=$1 [NC,L]
RewriteRule ^/.*/(.*).html$ index.php?page=$1 [NC,L]

To exclude a pattern you can do this:

RewriteCond %{REQUEST_URI} !^/src/
RewriteRule ^/(.*).html$ index.php?page=$1 [NC,L]

Also note, the above rules will do a 302 (temporary redirect) by default. Most folks really want a 301 (permanent redirect) especially if they care about SEO. [R=301,NC,L]

Upvotes: 0

icabod
icabod

Reputation: 7084

If I understand the last question (after your edit), you want to limit the second rewrite so that it will only rewrite pages, but not rewrite other subdirectories?

You can do that by changing the text that's matched to be "any character except a /":

RewriteRule ^([^/]*)\.html$ index.php?page=$1 [NC,L]

In regular expressions, the [ ] matches any specified character, and if you put ^ at the start, it matches any character that doesn't come between the square brackets... so here we're matching anything that isn't a slash.

Upvotes: 1

Related Questions