add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";

charset utf-8;

ssl_certificate /etc/nginx/ssl/allthebookmarks.com.pem;
ssl_certificate_key /etc/nginx/ssl/allthebookmarks.com.key;

error_page 404 /index.php;

location = /favicon.ico {
    log_not_found off;
    access_log off;
}

location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
}

location ~ /\.(?!well-known).* {
    deny all;
}

location ~ /\.ht {
    deny all;
}

location ~ ^/(doc|sql|setup)/ {
    deny all;
}

location ~ /\. {
    deny all;
}

location ~* \.(?:js|css|png|jpg|gif|ico|woff|tff|woff2|min.css.map)$ {
    access_log off;
    log_not_found off;
}

location /js/ {
    access_log off;
    log_not_found off;
    try_files $uri /index.php?error=js404&file=$uri;
}

location /css/ {
    access_log off;
    log_not_found off;
    try_files $uri /index.php?error=css404&file=$uri;
}

location /images/ {
    try_files $uri /index.php?error=image404&url=$uri;
}

location /uploads/ {
    try_files $uri /index.php?error=upload404&url=$uri;
}

location /errors/ {
    try_files $uri /index.php?error=$uri;
}

location /api/ {
    # Handle CORS for all requests
    if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
        add_header 'Access-Control-Allow-Headers' 'Authorization, DNT, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Range' always;
        add_header 'Access-Control-Expose-Headers' 'Content-Length, Content-Range' always;
    }
    # Handle preflight requests
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Allow-Headers' 'Authorization, DNT, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Range' always;
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain; charset=utf-8' always;
        return 204; # Return no content for preflight
    }

    rewrite ^/(.+)$ /index.php?url=$1&$args;
}

location / {
    rewrite ^/(.+)$ /index.php?url=$1&$args;
}
