简体   繁体   中英

Apache mod_rewrite is removing slashes and generally ignoring my rules

I'm at my wit's end, Stack Overflowers. Trying to do what I thought was a simple rewrite rule to replace slashes in the URL with tilde, then add a ".html" at the end. So my .htaccess is thus:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/(.+)/(.+)$ $1~$2 [N]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/([^/]+)$ $1.html [L]

Basically I'm running a repeated rule to replace all slashes with tildes one at time, then my final rule adds the ".html" -- because all our web files need to be in one folder (client request--silly, I know).

I've tested the pattern "part-one/part-two/part-three" here: http://martinmelin.se/rewrite-rule-tester/ and it only works if I chop off the initial slash and remove the rewrite conditions (which makes no sense b/c no filename I put in there should exist on that server), but that's not the case on my local server.

It should eventually read the file "part-one~part-two~part-three.html" but when I look at the Apache error log on my local machine, I get this:

File does not exist: /path/to/website/part-one

So it basically chops off the final two parts and never tries to add a ".html" -- so what on earth is going on?? Please help, mod_rewrite gurus!!

The reason why it wants you to remove the leading / is because the rewrite engine strips off the prefix (the leading slash of an URI) before it runs them through rules in an htaccess file. If you were using apache 1.3 or if the rules were in a non-per-directory context in the server or vhost config, then you'd need the leading slash in the rule's pattern:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/(.+)$ /$1~$2 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^/]+)$ /$1.html [L]

Additionally, you probably don't want the N flag, as you want rewrite to stop immediately in its current iteration. Also, a condition which first checks if the .html actually exists before you rewrite will prevent 500 internal server errors.

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