1

I am learning about url rewriting on .htaccess and is there any good book where i can learn.

I building an RESTfull webservices and i am working with pretty urls

Now I wrote below syntax in .htaccess file to achieve other urls.

RewriteRule ([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/users/([0-9a-zA-Z]) users.php?key=$1&format=$2&uid=$3
RewriteRule ([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/users users.php?key=$1&format=$2

Example 1

And url i tried and result are mentioned below

e.g.    http://localhost/site/key/format/users/user_id


http://localhost/rest/r123/json/users/pGQqAMbVQAFx

test.php

<?php print_r($_GET); ?>

And only get values for key and format not uid and value for key is php and i dont know how php value comes into exists

output.

Array
(
    [key] => php
    [format] => json
)

Example 2

http://localhost/rest/r123/json/users/

output

Array
(
    [key] => r123
    [format] => json
)

And is there any good book on url rewriting for beginners other than apache documentation.

4

1 回答 1

1

Your rules had few issues. Here is the fixed code:

RewriteRule /([a-z0-9]+)/([a-z0-9]+)/users/([0-9a-z]+)/? users.php?key=$1&format=$2&uid=$3 [L,QSA,NC]
RewriteRule /([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/users/?$ users.php?key=$1&format=$2 [L,QSA,NC]

Issues/Fixes in your code:

  1. After users/ you had this regex: ([0-9a-zA-Z]) which will match single character you probably meant ([0-9a-zA-Z]+)
  2. You should use flags L (Last Rule), QSA (Query String Append), NC (Ignore Case) after each Rewrite rule.
  3. Consider using end anchor $ to avoid matching unwanted URIs.
  4. Use / at the start of regex to avoid matching unwanted URIs.
  5. Instead of [A-Za-z0-9] you can use [a-z0-9] and use NC flag as described above.

Read more about mod_rewritw flags: https://httpd.apache.org/docs/current/rewrite/flags.html

于 2013-04-26T10:02:31.443 回答