Nginx Replace Characters in rewrite?

2019-05-30 00:47发布

问题:

Say you have a URL www.answers.mydomain.com/category/hello_world-123.html but you want to rewrite the path part as /category/hello-world

How would you go about that with an nginx rewrite? Basically how can I format the $1 variable?

 

     server{
       listen 80;
       server_name  ~^(?<subdomain>.+)\.bg\.com$
       root /home/dan/Projects/rewrite-example;


       set $PREFERRED_DOMAIN $scheme://www.bg.com;

       if ($subdomain ~* answers) {
         rewrite ^(.*)$ $PREFERRED_DOMAIN/questions$1 permanent;
       }
     } 

 

回答1:

 server{
     listen 80;
     server_name  answers.bg.com;

     rewrite ^(.+/[a-z]+)-\d+\.html$ http://www.bg.com$1 permanent;
     rewrite ^(.+/[a-z]+)_([a-z]+)-\d+\.html$ http://www.bg.com$1-$2 permanent;
     rewrite ^(.+/[a-z]+)_([a-z]+)_([a-z]+)-\d+\.html$
             http://www.bg.com$1-$2-$3 permanent;
     rewrite ^(.+/[a-z]+)_([a-z]+)_([a-z]+)_([a-z]+)-\d+\.html$
             http://www.bg.com$1-$2-$3-$4 permanent;
     rewrite ^(.+/[a-z]+)_([a-z]+)_([a-z]+)_([a-z]+)_([a-z]+)-\d+\.html$
             http://www.bg.com$1-$2-$3-$4-$5 permanent;
 }
  • http://nginx.org/en/docs/faq/variables_in_config.html
  • http://wiki.nginx.org/IfIsEvil
  • http://wiki.nginx.org/Pitfalls
  • http://nginx.org/en/docs/http/converting_rewrite_rules.html


标签: nginx rewrite