Is it somehow possible to run a javascipt code from Nginx in the web page when a particular url is opened from a browser by a user? For example when user opens https://example.net/test/page , javascript is executed in that web page.
Current Nginx settings:
server {
listen 443 ssl;
server_name example.net;
access_log /var/log/nginx/example.net.ssl.access.log;
error_log /var/log/nginx/example.net.ssl.error.log;
ssl_certificate /etc/letsencrypt/live/example.net/cert.pem;
ssl_certificate_key /etc/letsencrypt/live/example.net/privkey.pem;
location / {
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://localhost:8080;
}
}
How can I edit these settings in order to call a javascript from the "/path/to/file.js" to execute it only when user opens https://example.net/test/page ? In other pages script should't be executed. I would really appreciate any advice. Thank you!
You can try to use nginx SubFilter module to append a script to the document returned from the upstream. For example, you can replace the </head>
tag with the <script src="/path/to/script.js"></script></head>
string:
map $uri $script {
# only when URI is '/test/page'
/test/page '<script src="/path/to/script.js"></script>';
# default value will be an empty string
}
server {
...
location / {
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://localhost:8080;
sub_filter '</head>' '$script</head>';
}
# only one special location to serve locally
location = /path/to/script.js {
alias /full/path/to/script.js;
}
}
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.