I’d like to redirect what follows a URI, but I keep running into trouble.
Basically, I’d like /from/here/1234
redirected to /to/there.php?id=1234
. But I can only get it to work if the URI is formatted with something after my pattern, such as /form/here/1234/edit
.
This is the “working” rule:
RewriteEngine on
RewriteCond "%{REQUEST_URI}" !-d
RewriteRule ^from/here/(.*)/edit/?$ /to/there.php?id=$1
I have tried it with and without the RewriteCond
, with the following alterations:
-
If I remove
/edit
, so that the rule isRewriteRule ^from/here/(.*)/?$ /to/there.php?id=$1`
I get an “Internal Server Error”, and “Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.”
I cannot access
/from/here
or/from/here/
with this rule. -
If I add a leading slash, remove
/edit
and?
, so that the rule isRewriteRule ^/from/here/(.*)/$ /to/there.php?id=$1
I can access
/from/here
and/from/here/
with this rule, but not/from/here/1234
(404).I created a test 404 page just to print the
$_SERVER
variable, and nothing looks strange with theREQUEST_URI
(i.e. showing as/from/here/1234
). -
If I remove
/edit
and?
, so that the rule isRewriteRule ^from/here/(.*)/$ /to/there.php?id=$1
It works only if there is a trailing slash, unless I add the rule
RewriteRule ^from/here/([a-z0-9-]+)$ /from/here/$1/ [NC]
While this works, it just doesn’t feel right…
I have to be missing something simple/fundamental here, because I have struggled to find anything helpful on my own (which almost always means I’ve boneheadedly missed something “palm-face”/”head-wall”-worthy). I’m not exceedingly familiar with editing the .htaccess file, so that hasn’t helped matters.
TL;DR – I would like to redirect what follows a slash, but only if there is in fact something that follows it. Forward /from/here/1234
, but not /from/here
or /from/here/
.
2
Answers
I knew it... the regex was too inclusive. Changed the rule to
And all is well.
The simplest modification is to change
.*
to.+
so that there must be something, anything following/from/here/
.If you don’t want a trailing slash to be included in
$1
then you can make.+
non-greedy by appending a question mark. Making it non-greedy will ensure that/?
captures any trailing slash rather than.+
doing so.