Nginx 重写规则 - 附加语言前缀

Nginx 重写规则 - 附加语言前缀

我有一个网站spanish.com。我希望用户加载“es”目录下的页面,即spanish.com/es。例如:

用户应该看到: spanish.comspanish.com/es已加载

用户看到spanish.com/samplepagespanish.com/es/samplepage已加载


我试过

server {
    listen 80;
    server_name www.spanish.com;
    return 301 $scheme://spanish.com$request_uri;
} 

server {
    listen 80;
    server_name spanish.com;
    limit_conn arbeit 32;

    rewrite ^(.*)$ http://$host/es/$1 permanent;

    ## Access and error logs.
    access_log /var/log/nginx/spanish.com_access.log;
    error_log /var/log/nginx/spanish.com_error.log;

    ...
}

但它会导致无限重定向到http://spanish.com/es/es/es/es/es/es/es/...


另外更新
,如何从重写规则中排除文件?就像在 apache 中一样?

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

答案1

我是这样度过难关的:

## for the homepage
location = / {
    rewrite ^ /es;
}

## for the rest of the pages, excluding locations beginning
## with /<2char-lang-prefix>/*
## also excludes locations having only 3 characters, e.g. "/nb"
location ~* "^/(?!.{2,2}/).{3}.*$" {
    rewrite "^/(.*)$" /es/$1;
}

相关内容