-->

.htaccess rewrite rule with static files gives me

2019-08-11 03:18发布

问题:

My project (Silex) has a front controller web/index.php and assets in web/css/*, web/img/* and so on. I've placed the following .htaccess file in the root of the public html folder:

<IfModule mod_rewrite.c>
    Options -MultiViews

    RewriteEngine On
    RewriteBase web
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [QSA,L]
</IfModule>

Every request should be rewrited to web folder (RewriteBase web directive) and if file doesn't exist (!-f) it should be routed to the front controller.

This is not working:

<img src="/img/myimage.png" alt="" />

File myimage.png exists, but request for /img/myimage.png gives me a 404 folder. If I modify the path to /web/img/mmyimage.png it works.

Is there something I'm missing?

回答1:

You could try routing the css and img folders explicitly:

RewriteCond %{DOCUMENT_ROOT}/web%{REQUEST_URI} -f
RewriteRule ^(css|img) /web%{REQUEST_URI} [L]

You'd need to add that right before the condition for the index.php routing rule.



回答2:

Replace your .htaccess with this code:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

## If the request is for a valid directory
RewriteCond %{REQUEST_FILENAME} -d [OR]
## If the request is for a valid file
RewriteCond %{REQUEST_FILENAME} -f [OR]
## If the request is for a valid link
RewriteCond %{REQUEST_FILENAME} -l
## don't do anything
RewriteRule ^ - [L]

# if requested files exists in /web then forward it there
RewriteCond %{DOCUMENT_ROOT}/web/$1 -f
RewriteRule ^(.+?)/?$ /web/$1 [L]

# if requested files doesn't exist in /web then forward it to index.php
RewriteCond %{DOCUMENT_ROOT}/web/$1 !-f
RewriteRule ^(.+?)/?$ /web/index.php [L]


回答3:

if your server is running Apache >= 2.2.16 you can use:

FallbackResource /index.php

in your .htaccess instead of

<IfModule mod_rewrite.c>
    Options -MultiViews

    RewriteEngine On
    RewriteBase web
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [QSA,L]
</IfModule>

See also Apache’s fallbackresource: your new .htaccess command for more information.



回答4:

You need to change web to /web as Kyra mentioned.

Options -MultiViews

RewriteEngine On
RewriteBase /web
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

But that's not going to solve your issue.

Main problem is your DocumentRoot is pointing to /path/to/project and it should point to /path/to/project/web



回答5:

I managed to fix it with these lines:

<IfModule mod_rewrite.c>
    Options -MultiViews

    RewriteEngine On

    RewriteCond %{DOCUMENT_ROOT}/web/$1 -f
    RewriteRule ^(.+?)/?$ /web/$1 [L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ web/index.php [QSA,L]
</IfModule>