How i can translate uppercase to lowercase letters in a rewrite rule in nginx web server?

前端 未结 5 1603
鱼传尺愫
鱼传尺愫 2020-12-01 04:57

I need to translate the address:

www.example.com/TEST in ---> www.example.com/test

相关标签:
5条回答
  • 2020-12-01 05:04

    i managed to achieve the goal using embedded perl:

    location ~ [A-Z] {
      perl 'sub { my $r = shift; $r->internal_redirect(lc($r->uri)); }';
    }
    
    0 讨论(0)
  • 2020-12-01 05:07

    Based on Adam's answer, I ended up using lua, as it's available on my server.

    set_by_lua $request_uri_low "return ngx.arg[1]:lower()" $request_uri;
    if ($request_uri_low != $request_uri) {
       set $redirect_to_lower 1;
    }
    if (!-f $request_uri) {
        set $redirect_to_lower "${redirect_to_lower}1";
    }
    if ($redirect_to_lower = 11) {
        rewrite . https://$host$request_uri_low permanent;
    }
    
    0 讨论(0)
  • 2020-12-01 05:08

    Yes, you are going to need perl. If you are using Ubuntu, instead of apt-get install nginx-full, use apt-get install nginx-extras, which will have the embedded perl module. Then, in your configuration file:

      http {
      ...
        # Include the perl module
        perl_modules perl/lib;
        ...
        # Define this function
        perl_set $uri_lowercase 'sub {
          my $r = shift;
          my $uri = $r->uri;
          $uri = lc($uri);
          return $uri;
        }';
        ...
        server {
        ...
          # As your first location entry, tell nginx to rewrite your uri,
          # if the path contains uppercase characters
          location ~ [A-Z] {
            rewrite ^(.*)$ $scheme://$host$uri_lowercase;
          }
        ...
    
    0 讨论(0)
  • 2020-12-01 05:11
    location /dupa/ {
        set_by_lua $request_uri_low "return ngx.arg[1]:lower()" $request_uri;
        rewrite ^ https://$host$request_uri_low;
    }
    
    0 讨论(0)
  • 2020-12-01 05:23
    location ~*^/test/ {
      return 301 http://www.example.com/test;
    }
    

    A location can either be defined by a prefix string, or by a regular expression. Regular expressions are specified with the preceding “~*” modifier (for case-insensitive matching), or the “~” modifier (for case-sensitive matching).

    Soruce: http://nginx.org/en/docs/http/ngx_http_core_module.html#location

    0 讨论(0)
提交回复
热议问题