简体   繁体   中英

make a subdirectory show the content of a subdomain in nginx

I want to handle this:

blog.example.com => example.com/blog

blog.example.com/xxx => example.com/blog/xxx

in both samples there is nothing in blog subdirectory, and the code which should handle the blog is in subdomain. and just i want to show the url as showed above.

so. i want to forward(redirect without changing url) a subdirectory to subdomain.

is there any nginx configuration to do that?

You could have the following in your NGINX configuration.

server {
    listen 80;
    server_name blog.example.com;

    location / {
        return 301 $scheme://example.com/blog$request_uri;
    }
}

server {
    listen 80;
    server_name example.com;

    location /blog/ {
        <your code goes here>
    }
}

This takes any incoming requests to blog.example.com and redirects to example.com/blog along with the requested URI eg. blog.example.com/latest would redirect to example.com/blog/latest

location = /blog {
    return 302 /blog/;
}
location /blog/ {
    proxy_pass http://blog.example.com/;
}

Note that the / in proxy_pass is very important (without it the /blog part won't be stripped out in the request to upstream).

Some further details on the rationale of two independent location statements are available at https://serverfault.com/questions/562756/how-to-remove-the-path-with-an-nginx-proxy-pass/562850#562850 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM