简体   繁体   中英

.htaccess redirect all extension except css and javascript

I have a .htaccess file that redirect any extension to a non-extension url and displays the requestedfilename + .php . It works great with the (.*) part of the conditions.

When I type domain.com/file.html or domain.com/file.xml it displays the file.php and the url looks like domain.com/file .

I just would like to know how to exculde extensions like .js and .css from the expression. I don't want to redirect them to any other php file.

I tried things like: (.*!.(js|css)) instead of (.*) but I can't find a working solution...

The current code is this:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

#
# to display the name.php file for any requested extension (.*)
#
RewriteRule ^(.*)\.(.*) $1\.php

#
# to hide all type of extensions (.*) of urls
#
RewriteCond %{THE_REQUEST} ^[A-Z]+\s.+\.(.*)\sHTTP/.+
RewriteRule ^(.+)\.php $1 [R=301,L]

#
# no extension url to php
#
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.php [L]

</IfModule>

If your version of Apache supports it, you may be able to use "negative lookahead" and write the first RewriteRule like this:

RewriteRule ^(.*)\.(?!js|css)([^.]*)$ $1\.php

The [^.] part makes sure the (.*)\\. matches everything until the last . , "positioning" the negative lookahead at the right spot.

The main idea of redirect, is to forward something, when it's not there, so redirect will work only, if the requested url is not present. If you have a http://mysite.com/js/script.js file, it will always open that file as normal one.

So in your case, you don't need a specific redirect for css and js files, if they are actually there.

What you might need to do, is to point the full path of those files. In example:

  • http://mysite.com/js/script.js ( works )
  • /js/script.js ( works )
  • js/script.js ( will fail if you are under a different redirected directory then root )

etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM