1

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;
       }
     } 

 
Dan Watson
  • 90
  • 1
  • 9

1 Answers1

2
 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;
 }
VBart
  • 14,714
  • 4
  • 45
  • 49
  • Haha Back again :-) Ok so I kind of figured this but there is no way to do this recursively? It's ok if not I will just figure out the maximum length of my slugs. – Dan Watson Jul 20 '12 at 22:14
  • Using standard directives seems that no way. As alternative you can use [embedded perl](http://nginx.org/en/docs/http/ngx_http_perl_module.html) or [lua](http://wiki.nginx.org/HttpLuaModule) module. – VBart Jul 20 '12 at 22:36
  • See my answer here http://stackoverflow.com/questions/15912191/how-to-replace-underscore-to-dash-with-nginx/15934256#15934256 for a more efficient set of rewrite rules for character replacement. – Tobia Apr 10 '13 at 19:04