I'm having some problem regarding redirection in php, I used .htaccess for this but didn't succeed what I have is following 2 urls :
http://localhost/PROJECT_NAME/USERNAME/348
http://localhost/PROJECT_NAME/USERNAME
What I want here is :
1) if request came from
http://localhost/PROJECT_NAME/USERNAME/111
then it should go to:
http://localhost/PROJECT_NAME/index.php
2) If request came from
http://localhost/PROJECT_NAME/USERNAME
then it should go to:
http://localhost/PROJECT_NAME/detail.php
What I tried :
RewriteRule /(\w+)$ detail.php?id=$1 [L]
RewriteRule /(\w+)$ index.php [L]
RewriteRule /$ detail.php?id=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !index.php
RewriteCond %{REQUEST_URI} !(.*)/$
Didn't succeed after this it works fine for index but not for detail page, Please help guys thanks for your time in advance
Randheer
You have a couple issues here. First is the order and specificity of the matching.
First, a big gotcha for regex learners: \\w
(shorthand "word" character class) is equivalent to [A-Za-z0-9_]
. . . note the digits and underscore included!
Assuming that all of the IDs in the last fragment are only numeric and that usernames are all some mix of alpha, numberic, and/or underscore, you can just change the order of matching and use the \\d
(digit) character class first:
RewriteRule /(\d+)$ index.php [L]
RewriteRule /(\w+)$ detail.php?id=$1 [L]
That should cover your two examples.
You didn't outline a use case for the third rule, so I'm not exactly sure which URLs you're applying that to or how it would need to change. Here are some observation though:
RewriteCond
lines before the RewriteRule
they apply to. (Keep in mind that the expression of rewrite rule is actually checked first, then the conditions.) RewriteRule
expression would match anything ending with a trailing slash that isn't a real file. !-f
. And since you're matching with a trailing slash, you probably actually want to check that it's not a directory (versus file) using !-d
RewriteCond
expression is trying to capture within a negated expression (so it will never capture anything, or match for that matter since the effective expression is the same as the one in the rule, /$
) If you're trying to allow for a trailing slash on the username above, you could just add to what's already there:
RewriteRule /(\d+)$ index.php [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule /(\w+)/?$ detail.php?id=$1 [L]
If your use case for the third rule is something different, or if those RewriteCond
expressions were for a different rule below what you pasted, feel free to edit the question with the details and I can update my answer to address that case as well.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.