duffn
duffn

Reputation: 3760

Nginx redirect to SSL except for certain URL

I'd like to redirect all traffic to my site to SSL except for a single URL scheme. I would like this single scheme to return a response that indicates that this particular portion of the site is only available via SSL directly.

My site's conf file currently looks partially like this, which works fine for redirecting all traffic:

server {
    listen 80;
    server_name sub.example.com;
    rewrite ^ https://$server_name$request_uri? permanent;
}

server {
    listen 443;
    ssl on;
    ssl_certificate /etc/nginx/ssl/12345.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;
    server_name sub.example.com;

    client_max_body_size 4G;

    # ....
}

I'd like to do this:

Upvotes: 0

Views: 561

Answers (1)

user1600649
user1600649

Reputation:

Move the rewrite on the server level to the root location, then generate an error code for the API, set the error page for that status code and put your human readable description there. Let's say you return 403, which seems appropriate, then wet get this:

root /path/to/webroot;
location / {
    return 301 https://$host$request_uri;
}

location /api/ {
    error_page 403 /api_direct.html;
    deny all;
}

I've set the root so that the custom error page can be found, adjust to your needs.

Upvotes: 1

Related Questions