How can i split URL with htaccess

2020-04-21 02:24发布

For example:
google.com/en/game/game1.html
should be
google.com/index.php?p1=en&p2=game&p3=game1.html

how can i split URL and send index.php the part of "/" ?

1条回答
Lonely孤独者°
2楼-- · 2020-04-21 03:06

You can only achieve this if the query parameters are of a fixed length. Otherwise there is an other way but requires parsing of the path in the application.

Fixed length implementation

The following rule matches all three URL parts then rewrites them as named query arguments to index.php.

RewriteRule ^([^/]+)/([^/]+)/(.+)$ index.php?p1=$1&p2=$2&p3=$3

This rewrites:

/en/game/game1.html

To:

/index.php?p1=en&p2=game&p3=game1.html

Unknown length implementation

# Don't rewrite if file exist. This is to prevent rewriting resources like images, scripts etc
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php?path=$0

This rewrites:

/en/game/game1.html

To:

/index.php?path=en/game/game1.html

Then you can parse the path in the application.


Edit:) To make it so the rewrite rule only matches if the first level of the URL consists of two characters do:

RewriteRule ^([a-zA-Z]{2})/([^/]+)/(.+)$ index.php?p1=$1&p2=$2&p3=$3

You can also do it for the unknown length implementation so:

RewriteRule ^[a-zA-Z]{2}/ index.php?path=$0
查看更多
登录 后发表回答