Answers:
我也在Nginx Wiki和其他博客上进行了研究,最好的性能方法是执行以下操作:
使用nginx从www.example.com重定向到example.com(在撰写本文时为1.0.12版)。
server {
server_name www.example.com;
rewrite ^ $scheme://example.com$request_uri permanent;
# permanent sends a 301 redirect whereas redirect sends a 302 temporary redirect
# $scheme uses http or https accordingly
}
server {
server_name example.com;
# the rest of your config goes here
}
当请求到达example.com时,不使用if语句提高性能。而且它使用$ request_uri而不是创建$ 1匹配项来对重写收费(请参见Nginx常见陷阱页面)。
资料来源:
经过一番摸索和一些失误后,这里是解决方案。我遇到的问题是要确保使用“ http://example.com $ uri”。在$ uri前面插入/会导致重定向到http://example.com//
server {
listen 80;
server_name www.example.com;
rewrite ^ http://example.com$uri permanent;
}
# the server directive is nginx's virtual host directive.
server {
# port to listen on. Can also be set to an IP:PORT
listen 80;
# Set the charset
charset utf-8;
# Set the max size for file uploads to 10Mb
client_max_body_size 10M;
# sets the domain[s] that this vhost server requests for
server_name example.com;
# doc root
root /var/www/example.com;
# vhost specific access log
access_log /var/log/nginx_access.log main;
# set vary to off to avoid duplicate headers
gzip off;
gzip_vary off;
# Set image format types to expire in a very long time
location ~* ^.+\.(jpg|jpeg|gif|png|ico)$ {
access_log off;
expires max;
}
# Set css and js to expire in a very long time
location ~* ^.+\.(css|js)$ {
access_log off;
expires max;
}
# Catchall for everything else
location / {
root /var/www/example.com;
access_log off;
index index.html;
expires 1d;
if (-f $request_filename) {
break;
}
}
}
请在SO中访问此问题:https : //stackoverflow.com/a/11733363/846634
从更好的答案:
实际上,您甚至不需要重写。
server {
#listen 80 is default
server_name www.example.com;
return 301 $scheme://example.com$request_uri;
}
server {
#listen 80 is default
server_name example.com;
## here goes the rest of your conf...
}
我的回答是越来越多的投票,但以上情况也是如此。rewrite
在这种情况下,您永远不要使用a 。为什么?因为nginx必须处理并开始搜索。如果您使用return
(应该在任何Nginx版本中可用),它将直接停止执行。在任何情况下,这都是首选。
要重定向到非www,请修改vhost文件:
server {
listen 80;
server_name www.example.com;
rewrite ^/(.*) http://example.com/$1 permanent;
}
“永久”将重定向转换为301重定向。在此代码块之后,您可以配置没有www的域。
要将非www重定向到www:
server {
listen 80;
server_name example.com;
rewrite ^/(.*) http://www.example.com/$1 permanent;
}
萨西
顺便说一句,要使用Nginx进行完整的VPS设置,请在我的网站guvnr.com上查看VPS圣经,我希望这很方便!
这是我用的:
# ---------------------------------------
# vHost www.example.com
# ---------------------------------------
server {
##
# Redirect www.domain.tld
##
server_name www.example.com;
rewrite ^(.*) http://example.com$1 permanent;
}
# ---------------------------------------
# vHost example.com
# ---------------------------------------
server {
# Something Something
}
server {}
配置块之后进行重写。