Path: blob/main/xml/cn/docs/http/converting_rewrite_rules.xml
1 views
<!--1Copyright (C) Igor Sysoev2Copyright (C) Nginx, Inc.3-->45<!DOCTYPE article SYSTEM "../../../../dtd/article.dtd">67<article name="转换rewrite规则"8link="/cn/docs/http/converting_rewrite_rules.html"9rev="1"10lang="cn">111213<section name="重定向到主站">1415<para>16共享站点的管理员,习惯于<i>只</i>在Apache下使用.htaccess文件配置<i>所有</i>信息,通常会将下面规则1718<programlisting>19RewriteCond %{HTTP_HOST} example.org20RewriteRule (.*) http://www.example.org$121</programlisting>2223翻译成这样:2425<programlisting>26server {27listen 80;28server_name www.example.org example.org;29if ($http_host = example.org) {30rewrite (.*) http://www.example.org$1;31}32...33}34</programlisting>35</para>3637<para>38这种做法是错的,复杂而且低效。正确的方式是为<literal>example.org</literal>定义一个单独的服务器:3940<programlisting>41server {42listen 80;43server_name example.org;44return 301 http://www.example.org$request_uri;45}4647server {48listen 80;49server_name www.example.org;50...51}52</programlisting>5354<note>55在0.9.1版本(含)以前,可以这样实现重定向:56<programlisting>57rewrite ^ http://www.example.org$request_uri?;58</programlisting>59</note>6061</para>6263</section>646566<section>6768<para>69再举一个例子,处理一个和刚才相反的逻辑:既不是来自<literal>example.com</literal>,又不是来自<literal>www.example.com</literal>:7071<programlisting>72RewriteCond %{HTTP_HOST} !example.com73RewriteCond %{HTTP_HOST} !www.example.com74RewriteRule (.*) http://www.example.com$175</programlisting>7677应该按下面这样分开定义<literal>example.com</literal>、<literal>www.example.com</literal>和其他站点:7879<programlisting>80server {81listen 80;82server_name example.com www.example.com;83...84}8586server {87listen 80 default_server;88server_name _;89return 301 http://example.com$request_uri;90}91</programlisting>9293<note>94在0.9.1版本(含)以前,可以这样实现重定向:95<programlisting>96rewrite ^ http://example.com$request_uri?;97</programlisting>98</note>99100</para>101102</section>103104105<section id="converting_mongrel_rules"106name="转化混合规则">107108<para>109典型的混合规则如下:110111<programlisting>112DocumentRoot /var/www/myapp.com/current/public113114RewriteCond %{DOCUMENT_ROOT}/system/maintenance.html -f115RewriteCond %{SCRIPT_FILENAME} !maintenance.html116RewriteRule ^.*$ %{DOCUMENT_ROOT}/system/maintenance.html [L]117118RewriteCond %{REQUEST_FILENAME} -f119RewriteRule ^(.*)$ $1 [QSA,L]120121RewriteCond %{REQUEST_FILENAME}/index.html -f122RewriteRule ^(.*)$ $1/index.html [QSA,L]123124RewriteCond %{REQUEST_FILENAME}.html -f125RewriteRule ^(.*)$ $1/index.html [QSA,L]126127RewriteRule ^/(.*)$ balancer://mongrel_cluster%{REQUEST_URI} [P,QSA,L]128</programlisting>129130转换成nginx配置应该是这样:131132<programlisting>133location / {134root /var/www/myapp.com/current/public;135136try_files /system/maintenance.html137$uri $uri/index.html $uri.html138@mongrel;139}140141location @mongrel {142proxy_pass http://mongrel;143}144</programlisting>145</para>146147</section>148149</article>150151152