Search code examples
apache.htaccessmod-rewrite

.htaccess rewrite file path favicon.ico to core/favicon.ico


I am doing something wrong with writing my .htaccess syntax and what exactly I am unsure.

I have a file called /core/favicon.ico.

Now I want when the browser requests /favicon.ico it to have the server display: /core/favicon.ico.

The contents of my .htaccess is currently

<IfModule mod_rewrite.c>
    RewriteEngine on

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ core/index.php?url=$1 [QSA,L]
    
    RewriteRule ^favicon.ico core/favicon.ico [NC,L]
</IfModule>

The previous rewrite rule is needed for the functioning of my system.

RewriteRule ^(.*)$ core/index.php?url=$1 [QSA,L]

And that rule works fine.


Solution

  • RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ core/index.php?url=$1 [QSA,L]
    
    RewriteRule ^favicon.ico core/favicon.ico [NC,L]
    

    You've basically just got your rules in the wrong order. Presumably /favicon.ico does not exist, so the first rule rewrites the request to core/index.php?url=favicon.ico first and processing stops.

    You need to reverse the two rules (and backslash-escape the dot and add the end-of-string anchor). For example:

    RewriteRule ^favicon\.ico$ core/favicon.ico [NC,L]
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ core/index.php?url=$1 [QSA,L]
    

    Aside: This does not rewrite requests for the "homepage" (the document root), so presumably you have something else that handles that? Otherwise, I would expect you need to set the DirectoryIndex accordingly at the top of the file. For example:

    DirectoryIndex /core/index.php
    

    Note that the url parameter will be absent for such requests (to the "homepage").