How to replace underscore to dash with Nginx

前端 未结 3 1933
日久生厌
日久生厌 2020-11-30 14:30

I\'m using Nginx for the first time ever, and got basically no knowledge of it.

I need to replace \"_\" with \"-\" in 100+ URL. I figured there must be an easy way t

3条回答
  •  误落风尘
    2020-11-30 15:26

    This comes past due time, but I must specify that the answer above needs to be corrected as the use of n different numbers of rewirtes where n is the amount of underscores present in the URL is totally unnecesary. This problem can be solved using 3 different location directives and rewrite rules while concidering the following scenarios in their regular expresion:

    1. There are one or more underscores at the END of the url.
    2. There are one or more underscores at the START of the url
    3. There are one or more undersocres at the MIDDLE of the url

              location ~*^/(?\_+)(?[a-zA-Z0-9\-]*)$ { 
              return 301 $scheme://$host/-$t2; 
              }
      
              location ~*^/(?[a-zA-Z\_0-9\-]*)(?\_+)$ { 
              return 301 $scheme://$host/$t2-; 
              }
      
              location ~*^/(?[a-zA-Z0-9\-]*)(?\_+)(?[a-zA-Z0-9\-]*)$ { 
              return 301 $scheme://$host/$t2-$t3; 
              }
      

    This three directives will recursively replace all the underscores with '-' untill none are left

    -BeWilled

提交回复
热议问题