简体   繁体   English

apache .htaccess url重写不能不加斜杠

[英]apache .htaccess url rewrite doesn't work without slash

I am using Apache, trying to map different domain into different directory using .htaccess. 我正在使用Apache,尝试使用.htaccess将不同的域映射到不同的目录。 Users access different directory when they type different domains. 用户键入不同的域时将访问不同的目录。 I use the rules below: 我使用以下规则:

RewriteCond %{HTTP_HOST}   ^(www.)?mydomain.com$

RewriteCond %{REQUEST_URI}   !^/domaindir/

RewriteCond %{REQUEST_FILENAME}  !-f
RewriteCond %{REQUEST_FILENAME}  !-d

RewriteRule ^(.*)$   /domaindir/$1/ [L]

Everything works fine, except when I type domain.com/dir(without /), the browser will redirect to domain.com/domaindir/dir, I just want it stay in domain.com/dir. 一切正常,除了当我键入domain.com/dir(不带/)时,浏览器将重定向到domain.com/domaindir/dir,我只希望它停留在domain.com/dir中。 If I add / in the end, it will work fine. 如果最后添加/,它将正常工作。

Does anyone knows how to fix this? 有谁知道如何解决这个问题?


Thank you anubhava,after using your code,I got another problem. 谢谢anubhava,使用您的代码后,我遇到了另一个问题。 when I typed mydomain.com,I will got 404,I don't know why it just access index.php instead of index.html,but if I typed mydomain.com/dir, it can fetch the index.html and works fine.the error log is below 当我键入mydomain.com时,我会得到404,我不知道为什么它只访问index.php而不是index.html,但是如果我键入mydomain.com/dir,它可以获取index.html并正常工作。错误日志如下

[perdir D:/xampp/htdocs/] strip per-dir prefix: D:/xampp/htdocs/ -> 
[perdir D:/xampp/htdocs/] applying pattern '^((?!domaindir/).*?)/?$' to uri ''
[perdir D:/xampp/htdocs/] strip per-dir prefix: D:/xampp/htdocs/ -> 
[perdir D:/xampp/htdocs/] applying pattern '^((?!domaindir/).+?)/?$' to uri ''
[perdir D:/xampp/htdocs/] pass through D:/xampp/htdocs/
[perdir D:/xampp/htdocs/] strip per-dir prefix: D:/xampp/htdocs/index.php -> index.php
[perdir D:/xampp/htdocs/] applying pattern '^((?!domaindir/).*?)/?$' to uri 'index.php'

I still found stay in mydomain.com/dir will cause many files 404,how can I redirect to mydomain.com/dir/,thanks. 我仍然发现留在mydomain.com/dir中会导致很多文件404,我如何重定向到mydomain.com/dir/,谢谢。

That is because of mod_dir adding a trailing slash for directories. 这是因为mod_dir在目录后添加了斜杠。

Try this code instead: 请尝试以下代码:

DirectorySlash off
RewriteEngine On

RewriteCond %{HTTP_HOST} ^(www\.)?mydomain\.com$
RewriteCond %{REQUEST_FILENAME}  !-f
RewriteCond %{REQUEST_FILENAME}  !-d
RewriteRule ^((?!domaindir/).*)$ domaindir/$1 [L,NC]

# add a trailing slash now
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_URI} !-f
RewriteCond %{THE_REQUEST} \s/+(.*?)[^/][?\s]
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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