> For the complete documentation index, see [llms.txt](https://docshome.gitbook.io/nginx-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docshome.gitbook.io/nginx-docs/how-to/zhuan-huan-zhong-xie-gui-ze.md).

# 转换重写规则

## 重定向到主站点

使用共享主机的用户以前仅使用 Apache 的 `.htaccess` 文件来配置一切，通常翻译下列规则：

```
RewriteCond  %{HTTP_HOST}  example.org
RewriteRule  (.*)          http://www.example.org$1
```

像这样：

```
server {
    listen       80;
    server_name  www.example.org  example.org;
    if ($http_host = example.org) {
        rewrite  (.*)  http://www.example.org$1;
    }
    ...
}
```

这是一个错误、麻烦而无效的做法。正确的方式是为 `example.org` 定义一个单独的服务器：

```
server {
    listen       80;
    server_name  example.org;
    return       301 http://www.example.org$request_uri;
}

server {
    listen       80;
    server_name  www.example.org;
    ...
}
```

在 0.9.1 之前的版本，重定向可以通过以下方式实现：

```
rewrite ^ http://www.example.org$request_uri?;
```

另一个例子是使用了颠倒逻辑，即 **所有不是 `example.com` 和 `www.example.com` 的**：

```
RewriteCond  %{HTTP_HOST}  !example.com
RewriteCond  %{HTTP_HOST}  !www.example.com
RewriteRule  (.*)          http://www.example.com$1
```

应该简单地定义 `example.com`、`www.example.com` 和 **其他一切**：

```
server {
    listen       80;
    server_name  example.com www.example.com;
    ...
}

server {
    listen       80 default_server;
    server_name  _;
    return       301 http://example.com$request_uri;
}
```

在 0.9.1 之前的版本，重定向可以通过以下方式实现：

```
rewrite ^ http://example.com$request_uri?;
```

## 转换 Mongrel 规则

典型的 Mongrel 规则：

```
DocumentRoot /var/www/myapp.com/current/public

RewriteCond %{DOCUMENT_ROOT}/system/maintenance.html -f
RewriteCond %{SCRIPT_FILENAME} !maintenance.html
RewriteRule ^.*$ %{DOCUMENT_ROOT}/system/maintenance.html [L]

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.*)$ $1 [QSA,L]

RewriteCond %{REQUEST_FILENAME}/index.html -f
RewriteRule ^(.*)$ $1/index.html [QSA,L]

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ $1.html [QSA,L]

RewriteRule ^/(.*)$ balancer://mongrel_cluster%{REQUEST_URI} [P,QSA,L]
```

应该转换为：

```
location / {
    root       /var/www/myapp.com/current/public;

    try_files  /system/maintenance.html
               $uri  $uri/index.html $uri.html
               @mongrel;
}

location @mongrel {
    proxy_pass  http://mongrel;
}
```

## 原文档

<http://nginx.org/en/docs/http/converting_rewrite_rules.html>
