How do I exclude CSS, JS, JPG, GIF files from mod_rewrite rules?

前端 未结 4 1088
挽巷
挽巷 2021-01-14 06:26

This is what I have so far:

RewriteRule ^([A-Za-z0-9_]*)/?$ index.php?page=$1 [NC]
RewriteRule ^([A-Za-z0-9_]*)/([A-Za-z0-9_]*)/?$ index.php?page=$1/$2 [NC]
         


        
相关标签:
4条回答
  • 2021-01-14 06:51

    ... it assumes the css is located in /whatever/ssi/*.css.
    I just want to be able to write a condition that says "if it's a css file, don't apply these rules."

    This translates directly to

    RewriteCond %{REQUEST_URI} !^/whatever/ssi/[^/]+\.css$
    RewriteRule ...
    
    0 讨论(0)
  • 2021-01-14 06:57

    Anticipating you're using Apache with mod_rewrite module, you should try the RewriteCond Directive. The following example excludes all the matches from RewriteCond for the following line with the RewriteRule Directive. The rules are basically regular expression. The one in my example excludes everything which starts with either favicon.ico as well as with css, which is the folder, where my Stylesheets resides.

    RewriteEngine On
    RewriteCond $1 !^(favicon\.ico|favicon\.png|media|robots\.txt|crossdomain\.xml|css|js)
    RewriteRule ^(.*)$ index.php/$1 [L]
    

    Further reading: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html#rewritecond

    0 讨论(0)
  • 2021-01-14 07:02

    The problem that you are experiencing is not that the mod_rewrite is being applied to css files, but rather that the paths in your html to your css is relative. The browser is simply requesting the css from the correct relative path. You really have two options.

    1. Make your paths to your css relative to the domain instead of to the page (e.g. use /ssi/styles.css instead of ssi/styles.css)
    2. Create a rewrite rule to redirect all css to the correct URL. (e.g. RewriteRule (*.css) /ssi/$1
    0 讨论(0)
  • 2021-01-14 07:05

    I guess my solution will be the most empirical one but it worked:

    RewriteEngine On
    
    RewriteBase /
    
    RewriteRule ^([a-z0-9-]+)$ /?page=$1 [NC,L]
    
    RewriteRule ^([a-z0-9-]+)/([a-z0-9-]+)$ /?page=$1&action=$2 [NC,L]
    

    That will translate http://example.com/?page=contact&action=send to http://example.com/contact/send My page values were only alphanumeric and contain minus sign as word separator but you can replace the values to match whatever you need.

    And, of course you need to prefix all of your js, css, img directories with a slash in the pages. So css/style.css would be /css/style.css or use absolute url.

    0 讨论(0)
提交回复
热议问题