Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

php - Pretty URLs with .htaccess

I have a URL http://localhost/index.php?user=1. When I add this .htaccess file

Options +FollowSymLinks
RewriteEngine On

RewriteRule ^user/(.*)$ ./index.php?user=$1

I will be now allowed to use http://localhost/user/1 link. But how about http://localhost/index.php?user=1&action=update how can I make it into http://localhost/user/1/update ?

Also how can I make this url http://localhost/user/add ? Thanks. Sorry I am relatively new to .htaccess.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to turn

http://www.yourwebsite.com/index.php?user=1&action=update

into

http://www.yourwebsite.com/user/1/update

You could use

Options +FollowSymLinks
RewriteEngine On

RewriteRule ^user/([0-9]*)/([a-z]*)$ ./index.php?user=$1&action=$2

To see the parameters in PHP:

<?php 
echo "user id:" . $_GET['user'];
echo "<br>action:" . $_GET['action'];
?>
  • The parenthesis in the .htaccess are groups that you can call later. with $1, $2, etc.
  • The first group I added ([0-9]*) means that it will get any numbers (1, 34, etc.).
  • The second group means any characters (a, abc, update, etc.).

This is, in my opinion, a little bit more clean and secure than (.*) which basically mean almost anything is accepted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...