Add slash to the end of every url (need rewrite rule for nginx)

前端 未结 9 894
慢半拍i
慢半拍i 2020-11-28 03:28

I try to get an \"/\" to every urls end:

example.com/art

should

example.com/art/

I use nginx as webserver.

I need the rewrite rule f

9条回答
  •  无人及你
    2020-11-28 03:52

    Odd that this is the first result in Google, but doesn't have a satisfactory answer. There are two good ways to do this I know of. The first is to straight-up check if the request will hit a file and only apply a rewrite condition if not. E.g.

    server {
       # ...
       if (!-f $request_filename) {
         rewrite [^/]$ $uri/ permanent;
       }
       location / {
          # CMS logic, e.g. try_files $uri $uri /index.php$request_uri;
       }
       # ...
    }
    

    The second, which many prefer as they'd rather avoid any use of if that isn't 100% necessary, is to use try_files to send the request to a named location block when it won't hit a file. E.g.

    server {
       # ...
       location / {
          try_files $uri $uri/ @cms;
       }
       location @cms {
          rewrite [^/]$ $uri/ permanent;
          # CMS logic, e.g. rewrite ^ /index.php$request_uri;
       }
       # ...
    }
    

提交回复
热议问题