mod_rewrite misbehaves if regex matches existing f

2019-09-06 02:02发布

I've got an .htaccess rule like this:

RewriteRule    ^z/([^/]+)$    y.html?$1    [NC,L]

This rule works fine. But if I change the rule slightly, to:

RewriteRule    ^y/([^/]+)$    y.html?$1    [NC,L]

When I try to load y/anything I get a 404 and the following message in the error log:

File does not exist: /var/www/y.html/anything

The only difference I can see is that z.html does not exist, but y.html does. At first I thought maybe the initial transform was triggering a recursive re-write, but I don't see how this could be. It should rewrite:

`y/anything`

to

`y.html?anything`

Which does NOT have a slash in it. In fact, the only problem with the re-written URL is that it has a slash where I specified a question mark. What is going on here?

It gets stranger. If I change the rewrite URL, e.g. to

RewriteRule    ^y/([^/]+)$    /q.html?$1    [NC,L] 

it STILL is telling me /var/www/y.html/anything not found, not q.html..

If I move y.html to y.js on the server, then it tells me /var/www/y.js/anything is not found. It really seems like it is somehow matching /dir/ and changing it to an existing file. Is there a default rule somewhere in apache that might do this?

I tried a hard reload in the browser, which had no effect.

Update: I tried to use RewriteLog to see what was going on with the re-writing. However, to do this I had move my rewrite entries to the VirtualHost section of my main config. After I did this the pattern matching completely stopped until I changed my rule to:

RewriteRule    ^/y/([^/]+)$    /y.html?$1    [NC,L]

After making this change, everything works as expected. So why can't I get it to work in the .htaccess file? Neither regex works properly there (with or without the leading slash).

2条回答
Rolldiameter
2楼-- · 2019-09-06 02:42

For anyone who runs into this problem in the future, the issue I was having was that MultiViews was interfering with my URL resolution. When I removed "MultiViews" from the list of options for the <Location/> in the <VirtualHost> the issue went away.

查看更多
相关推荐>>
3楼-- · 2019-09-06 02:51

Having the following in the htaccess file

RewriteEngine On                                                           
RewriteRule    ^z/([^/]+)$    /y.html?$1    [NC,L]
RewriteRule    ^y/([^/]+)$    /y.html?$1    [NC,L]

will show the contents of y.html

You might want to do a hard refresh of the page because if it was previously redirected to /y.html/anything, but then changed to /y.html?anything it might still be in a cache on your browser. Double check with your other browsers that the same thing is happening on them.

查看更多
登录 后发表回答