Search code examples
phpapache.htaccessurl-rewritingseo

how do I get rewrite rules working from the apache .htaccess while CSS and javascript files are not rewritten?


Been through other suggested questions but no luck. These is my .htaccess rewrite rules, mainly being done for SEO and user-friendliness purposes:

Options +SymLinksIfOwnerMatch

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_URI} !^/(images|css|js|scripts/.*)$
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_URI} !\.(?:css|js|jpe?g|gif|png)$ [NC]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    # RewriteRule ^dictionary/(.*) dictionary.php [NC,L]
    RewriteRule . /index.php [L]
    RewriteRule ^dict/[^/]+/[^/]+/(.+)$ $1  [L]
</IfModule>

If I uncomment the rewrite rule so any requests to www.xyz.com/dictionary and internally rewritten to www.xyz.com/dictionary.php, with any query string added to it, the entire site stops working.

What I would like is that any request to the folders JS, CSS, images and scripts is not rewritten (so I do not get /dictionary.images/xyz.jpg) and php files included in dictionary.php are not rewritten.

Any request to a anexisting directory is not touched, but if a directory that doesn't exist is rewritten to /index.php

How can I get the rewrite 'fake' directories rewritten please? I have about 5 more fake directories that I'd like to re-write, and the CSS, JavaScript and images are loaded from he correct paths?


Solution

  • Rewrite conditions only apply to the very next rule. When you insert the "dictionary" rule inbetween the index.php rule and its rewrite conditions above it, they stop applying to that rule and break your site. You need to add your new rule in some other place.

    I would suggest adding new lines to emphasize which conditions go with which rules.

    Your dict and dictionary rules need to go near the top so that those paths don't get handled by your front controller (index.php)

    Try:

    Options +SymLinksIfOwnerMatch
    
    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /
    
        RewriteRule ^dict/[^/]+/[^/]+/(.+)$ $1  [L]
    
        RewriteRule ^dictionary/(.*) dictionary.php [NC,L]
    
        RewriteCond %{REQUEST_URI} !^/(images|css|js|scripts/.*)$
        RewriteRule ^index\.php$ - [L]
    
        RewriteCond %{REQUEST_URI} !\.(?:css|js|jpe?g|gif|png)$ [NC]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /index.php [L]
    
    </IfModule>