apache .htaccess 将非 WWW 重定向到 WWW 保留 URI 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1685962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 18:22:40  来源:igfitidea点击:

.htaccess Redirect non-WWW to WWW preserving URI string

phpapache.htaccessmod-rewritecodeigniter

提问by Steven

I'm running the CodeIgniter platform, which uses .htaccess to accept URLs like

我正在运行 CodeIgniter 平台,它使用 .htaccess 来接受像

http://www.mysite.com/controller/function/argument

I currently use some .htaccess rewrites, namely (simplified):

我目前使用一些 .htaccess 重写,即(简化):

RewriteEngine On
RewriteCond %{REQUEST_URI} !^(/index\.php|/images|/assets)
RewriteRule ^(.*)$ /index.php/ [L]

I want to add a rewrite rule that redirects all non www requests to www. I also want the URI string following the domain name to stay the same in the redirect. For instance, if a user makes a request for http://mysite.com/controller/function/argument, I want the .htaccess file to rewrite the request in the browser as http://www.mysite.com/controller/function/argumentand then process the request.

我想添加一个重写规则,将所有非 www 请求重定向到 www。我还希望域名后面的 URI 字符串在重定向中保持不变。例如,如果用户发出请求http://mysite.com/controller/function/argument,我希望 .htaccess 文件在浏览器中重写请求http://www.mysite.com/controller/function/argument,然后处理请求。

回答by ekhaled

I had a similar problem, and this .htaccess works for me

我有一个类似的问题,这个 .htaccess 对我有用

RewriteEngine On                           

#This bit rewrites your host name to include www
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/ [R=301,NC,L]

#This bit does the codeigniter magic
RewriteCond %{REQUEST_FILENAME} !-f  
RewriteCond %{REQUEST_FILENAME} !-d  
RewriteRule ^(.*)$ /index.php/ [L]

回答by rossoft

It should be something like this:

它应该是这样的:

RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule (.*) http://www.example.com/ [R=301,L]

回答by starkeen

If you are on apache 2.4 ,You can use the following simple redirect :

如果您使用的是 apache 2.4,则可以使用以下简单重定向:

<if "%{HTTP_HOST} =='example.com'">
Redirect / http://www.example.com/
</if>