0

i need some help from the experts.

I have some rewrite rules:

post.php go to http://example.com/post/3/
RewriteRule ^post/([A-Za-z0-9-]+)/?$ post.php?id=$1 [NC,L]

It Works!

But, How can i add a new rewrite rule to the NEW Page Users.php after post/ID/ And get the ID in Users.php (Users.php?id=3)

Like this http://example.com/post/3/users

Thanks!

Mark
  • 3
  • 2
  • 4
  • So `/post/3/` must go to `/post.php?id=3`. That works. But also `/post/3/users/' should go to `/Users.php?id=3`? – Kaz Mar 11 '12 at 22:14

1 Answers1

3

If you want /post/3/users/ to go to /Users.php?id=3, you have to put that rule before your existing rule. Your existing rule matches /post/3/' which is a prefix of what this additional rule matches, so that rule will never fire if it is after.

# catch the longer URL first
RewriteRule ^post/([A-Za-z0-9-]+)/users/?$ Users.php?id=$1 [NC,L]

# No /users/ on it; rewrite to post.php
RewriteRule ^post/([A-Za-z0-9-]+)/?$ post.php?id=$1 [NC,L]

Another thing: you tagged your post with .htaccess. Does that mean your rewrites are in a .htaccess? If so, you should use RewriteBase because your rewrites are relative. Why it's working is probably that you are allowing a 1:1 correspondence between paths and URLs on your webserver.

In a per-directory context like .htaccess, mod_rewrite is working with path names, not URLs. But if you do a relative rewrite, the path is turned into a URL and fed back into the Apache's request handling chain to be processed over again. How the path is turned into a URL is that the contents of RewriteBase are added to the front. If you don't have RewriteBase then a silly thing happens: the path to your directory (that was removed for the RewriteRule is just tacked back on!).

Example: suppose your DocumentRoot is /var/www. Suppose the browser asks for the URL /foo. This gets translated to the path /var/www/foo If inside the .htaccess for /var/www/ you rewrite foo to bar (and RewriteBase is not set), then mod_rewrite will generate the URL /var/www/bar: it just takes the /var/www/ directory that was stripped off and puts it back on. Now that can be made to work: just make /var/www/ a valid URL going to that directory. For instance with

Alias /var/www /var/www # map /var/www URL to /var/www directory

But that is hacky. The right way is to have RewriteBase / in the .htaccess. So when foo is rewritten to bar, it just gets a / in front and becomes the url /bar. This is fed back to the server and will resolve back to the document root again "naturally".

I used hacks like that before I understood the rewriting. I even used / as a DocumentRoot! That made everything work out since then most URLs are paths: you don't have to think of URLs a an abstraction separate from your filesystem paths. But it's a dangerous, silly thing.

Kaz
  • 55,781
  • 9
  • 100
  • 149