I need to 301 redirect the contents of an entire directory to another directory with nginx. While my configuration works, it unfortunatelly also exposes the port number. This is I guess now a side effect since the inbound traffic for the specific domain is handled via HAProxy ACL rules to the 8000 port, while the url itself is port 80.

This is my nginx conf:

server {
    listen       8000;
    port_in_redirect off;
    location ~* ^/data/dir1/(.*)$ {
    return 301 /data/dir2/$1;

It redirects from URL:




How could I get rid of the 8000 inside the URL redirect?

The tmp workaround I have is to put :80 into the redirect but I fear that this will impact the URL google is listing as it includes a port number.

  • yes, same result. I now have return 301 http://$server_name:80/data/dir2/$1; as a quick fix but that adds the :80 into the URL – merlin Sep 14 '15 at 15:14

Can you try the following:

server {
    listen       8000;
    location ~* ^/data/dir1/(.*)$ {
    return 301 http://example.com/data/dir2/$1;
  • Thank you, that fixed it! Strange as I have put in the $server_name directive which should be the same. Anyway ... works now. – merlin Sep 14 '15 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.