Response
stringlengths
8
2k
Instruction
stringlengths
18
2k
Prompt
stringlengths
14
160
The problem is because $http_host inproxy_set_header Host $http_host;uses the host in your original request header, but what you really need is the host forwww.example2.com. $proxy_host will use the host in yourproxy_passdirective. seeEmbedded Variablesat the bottomhttp://nginx.org/en/docs/http/ngx_http_proxy_module.html$proxy_hostname and port of a proxied server as specified in the proxy_pass directive;And the reason it is not working forexample1.combutwww.example1.comI guess is because you didn't put the valueexample1.cominserver_namedirective.
I have configured my nginx on amazon ec2 for the urlwww.example1.com. I need to proxy passwww.example1.com/blogto my blogging hostwww.example2.com/blogwhich is hosted on bluehost ( shred hosting ) without changing the url in browser. Is it possible ?I tried many different combinations likelocation /blog { proxy_pass http://www.example2.com; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }without any luck.I could see in the log that nginx is trying to map to the IP instead of the domain which is the reason for the failure as shared hosting cannot recognize the ip but domain name.Any input/help will be really appreciated.
nginx proxy pass to external url
Here is what i did to my application. Every route ending with a '/' (except the root it self) will serveindex.html:location ~ ^/.+/$ { rewrite .* /index.html last; }You can also prefix your route :Backbone.history.start({pushState: true, root: "/prefix/"})and then :location ~ ^/prefix/ { rewrite .* /index.html last; }Or define a rule for each case.
I am trying to getnginxto work with mypushState-based URI handling thatbackbone.jsmanages for me in an Javascript app.Right now accessing URI's with one level, eg.example.com/usersworks well, but not two-level or deeper URI's, such asexample.com/users/all, which is mentioned in theBackbone documentation:For example, if you have a route of /documents/100, your web server must be able to serve that page, if the browser visits that URL directlySo, being far from acquainted with nginx's rewrite options, I am still sure that I can do something likerewrite ^ /index.html;to redirect everything to myindex.html, but loosing out on any eventual static files (images, javascript & css) stored on the same server which I need to be able to access.So what should I do instead with the below shown, current configuration, to make this work?server { listen 80; server_name example.com; location / { root /var/www/example.com; try_files $uri /index.html; } }
Rewriting nginx for pushState-URL's
Oh! Pleasedon't disable SELinux.Don't use/root— it's a trap!First — do youreallyneed to serve files from/root? That's actually the home directory for the rootuser account, not meant to be thewebroot.Instead, use/var/www/htmlor (my preference)/srv/www.If youdouse/root, make sure you're not exposing ssh keys orauthorized_keysfiles, database passwords, or anything similar. Using/rootto serve web pages is really just a bad idea all around. (But... no shame here: it's clearly confusing, and kind of a trap set by history due to the name 'root' being used for multiple concepts.)Make SELinux work for you!Second, rather than disabling SELinux (which, in this case, is protecting you from doing something dangerous), you should configure it properly. In Fedora Linux, the SELinux policy as designed so nginx shares this with other webservers, so, using/srv/www/yoursiteas the root,chcon -R -t httpd_sys_content_t /srv/www/yoursiteshould do it.(This answer should also apply to all of the "Enterprise Linux" distributions that are downstream from Fedora Linux — that is, RHEL, CentOS Linux, CentOS Stream, Alma Linux, Rocky Linux, etc., etc.)
I am installing nginx. Here is the steps I followed:Make index.html file in /root directoryedit /etc/nginx/nginx.conf. After edit it looks like this:user nginx; worker_processes 1; error_log /var/log/nginx/error.log; ... http { ... server { listen 80 default_server; server_name my_domain_name.com; root /root; ... }followingthisquestion I gave away permissions:gpasswd -a nginx rootchmod g+x /root(sorry, couldn't correctly format as code)I restarted server:service nginx restartI visited my_domain_name.com and got 403 error. /var/log/nginx/error.log content:"/root/index.html" is forbidden (13: Permission denied), client: 117.211.86.108, server: my_domain_name.com, request: "GET / HTTP/1.1", host: "my_domain_name.com"
nginx: "/root/index.html" forbidden (13: Permission denied)
How is your directory setup? Do you have a folderstaticin/home/user/www/oil/oil_database/static_files? In that case, the directive should look like this (note the trailing slash in/static/):location /static/ { autoindex on; root /home/user/www/oil/oil_database/static_files; }If you want to map the path/home/user/www/oil/oil_database/static_filesto the URL/static/, you have to eitherrename the folderstatic_filestostaticand use this directive:location /static/ { autoindex on; root /home/user/www/oil/oil_database/; }use an alias:location /static/ { autoindex on; alias /home/user/www/oil/oil_database/static_files/; }See the documentation on therootandaliasdirectives.
I'm running Django on Ubuntu Server 9.04.Django works well, but nginx doesn't return static files - always 404.Here's the config:server { listen 80; server_name localhost; #site_media - folder in uri for static files location /static { root /home/user/www/oil/oil_database/static_files; autoindex on; } #location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js|mov) { # root /home/user/www/oil/oil_database/static_files; # access_log off; # expires 30d; #} location / { root html; index index.html index.htm; # host and port to fastcgi server #fastcgi_pass 127.0.0.1:8080; fastcgi_pass unix:/home/user/www/oil/oil_database/oil.sock; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param QUERY_STRING $query_string; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_pass_header Authorization; fastcgi_intercept_errors off; } access_log /var/log/nginx/localhost.access_log; error_log /var/log/nginx/localhost.error_log; }Nginx version is 0.6.35.All directories exist and made 777 (debugging paranoia). The commented-out block doesn't help when I uncomment it.
Nginx doesn't serve static
You can useabortto raise an HTTP error by status code.from flask import abort @app.route('/badrequest400') def bad_request(): abort(400)
A consumer of my REST API says that on occasion I am returning a400 Bad Request-The request sent by the client was syntactically incorrect.error.My application (Python/Flask) logs don't seem to be capturing this, and neither do my webserver/Nginx logs.Edit: I would like to try to cause a 400 bad request in Flask for debugging purposes. How can I do this?Following James advice, I added something similar to the following:@app.route('/badrequest400') def bad_request(): return abort(400)When I call this, flask returns the following HTML, which doesn't use the "The request sent by the client was syntactically incorrect" line: 400 Bad Request Bad Request The browser (or proxy) sent a request that this server could not understand.(I'm not sure why it isn't including thetags.It appears to me that there are different variations of the 400 error message. For example, if I set a cookie to a value of length 50,000 (using Interceptor with Postman), I'll get the following error from Flask instead: Bad Request Bad Request Error parsing headers: 'limit request headers fields size' Is there a way to get Flask to through the different variations of 400 errors?
How to intentionally cause a 400 Bad Request in Python/Flask?
I had the same problem which was that I copy/pasted the config code from the web and some dirtyEOL(end of line) characters where there.The editor didn't show them, butnginxtreated them like a directive.Just deleted everyEOLand added again.
I have followed this websitehttp://raspberrypihelp.net/tutorials/24-raspberry-pi-webserverto setup the HTTP server nginx on my Raspberry Pi and try to setup a site callexample.com. But when I runsudo service nginx restart, it saidRestarting nginx: nginx: [emerg] unknown directive " " in /etc/nginx/sites-enabled/example.com:3Here is the code inexample.com.server { server_name example.com 192.168.1.88; access_log /srv/www/example.com/logs/access.log; error_log /srv/www/example.com/logs/error.log; root /srv/www/example.com/public/; location / { index index.php index.html index.htm; try_files $uri $uri/ /index.php?$args; } location ~ \.php$ { include /etc/nginx/fastcgi_params; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /srv/www/example.com/public$fastcgi_script_name; } location /phpmyadmin { root /usr/share/; index index.php index.html index.htm; location ~ ^/phpmyadmin/(.+\.php)$ { try_files $uri =404; root /usr/share/; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include /etc/nginx/fastcgi_params; } location ~* ^/phpmyadmin/(.+\.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt))$ { root /usr/share/; } } location /phpMyAdmin { rewrite ^/* /phpmyadmin last; } }I am just following the steps but it can't run successfully.
nginx: [emerg] unknown directive " " in /etc/nginx/sites-enabled/example.com:3
I have the same problem with my development server. After some internet search I've found this discussion (nginx, apache, and odd admin error) where the solution is to modify the proxy configuration of nginx.The configuration setting to modify is:proxy_set_header Host $host;the solution is to add the port number:proxy_set_header Host $host:$server_port;In my ngnix + apache2 (with worker mpm) + django now all works well.
I have a webapp built with Django. I'm currently running it off a laptop at home behind a router.I have the router configured to route all traffic sent to a specific port to that laptop.I have Nginx as a reverse proxy for Apache, using mod_wsgi to run Django.My problem is this: when I try to submit any POST form, the port # gets removed from the url (e.g. 209.245.23.201:1552/login/ becomes 209.245.23.201/login/)Naturally, this breaks. What causes this (Nginx, Apache, Django?) and how can I fix it?Thanks in advance.EDIT: It appears that the forms DO submit, but I think the redirect fails.EDIT 2: The problem is definitely either with Nginx, or the interaction between Nginx and Apache. I tried the setup with Apache as the only server, running django, and it worked fine. So either Nginx is dropping the port, or somehow Apache is getting confused by Nginx acting as the proxy.whatever
Http POST drops port in URL
You're pointing gunicorn atmysite:app, which is equivalent tofrom mysite import app. However, there is noappobject in the top (__init__.py) level import ofmysite. Tell gunicorn to call the factory.gunicorn "mysite:create_app()"You can pass arguments to the call as well.gunicorn "mysite:create_app('production')"Internally, this is equivalent to:from mysite import create_app app = create_app('production')Alternatively, you can use a separate file that does the setup. In your case, you already initialized anappinmanage.py.gunicorn manage:app
I have a Flask app I am trying to serve via Gunicorn.I am using virtualenv and python3. If I activate my venv cd to my app base dir then run:gunicorn mysite:appI get:Starting gunicorn Listening at http://127.0.0.1:8000 DEBUG:mysite.settings:>>Config() ... Failed to find application: 'mysite' Worker exiting Shutting down: master Reason: App failed to loadLooking in /etc/nginx/sites-available I only have the file 'default'. In sites-enabled I have no file.In my nginx.conf file I have:include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*;App structure:mysite #this is where I cd to and run gunicorn mysite:app --manage.py --/mysite ----settings.py ----__init__.pyinmanage.pyfor mysite I have following:logger.debug("manage.py entry point") app = create_app(app_name) manager = Manager(app) if __name__ == "__main__": manager.run()In__init__.pyfile:def create_app(object_name): app = Flask(__name__) #more setup here return appIn mysettings.pyin the app directoryclass Config(object): logger.debug(">>Config()") #this logs OK so gunicorn is at least starting in correct directoryFrom inside the virtualenv if I runprint(sys.path)I find a path to python and site-packages for this virtualenv.From what I have read to start gunicorn it's just a matter of installing it and running gunicorn mysite:appRunning gunicorn from the parent directory of mysite I get the same failed to find application: 'mysite', App failed to load error, but don't get the DEBUG...Config() logged (as we are clearly in the wrong directory to start in). Running gunicorn from mysite/mysite (clearly wrong) I get and Exception in worker process ereor, ImportError: No module named 'mysite'.Any clues as to how I can get gunicorn running?
Gunicorn failed to load Flask application
I've just solved a similar problem in python. In my case, it was solved by reducing the prefetch count on the consumer, so that it had fewer messages queued up in its receive buffer.My theory is that the receive buffer on the consumer gets full, and then RMQ tries to write some other message to the consumer's socket and can't due to the consumer's socket being full. RMQ blocks on this socket, and eventually timeouts and just closes the connection on the consumer. Having a smaller prefetch queue means the socket receive buffer doesn't get filled, and RMQ is able to write whatever bookkeeping messages it was trying to do and so doesn't timeout on its writes nor close the connection.This is just a theory though, but it seems to hold in my testing.In Python, setting the prefetch count can be done like so:subChannel.basicQos(10);(Thanks to @shawn-guo for reminding me to add this code snippet)
I've set up RabbitMQ in order to parse some 20.000 requests from an external API but it keeps timing out after a few minutes. It does get to correctly parse about 2000 out of the total 20.000 requests.The log file says:=INFO REPORT==== 16-Feb-2016::17:02:50 === accepting AMQP connection <0.1648.0> (127.0.0.1:33091 -> 127.0.0.1:5672) =ERROR REPORT==== 16-Feb-2016::17:03:21 === closing AMQP connection <0.1648.0> (127.0.0.1:33091 -> 127.0.0.1:5672): {writer,send_failed,{error,timeout}}I've already increased the heartbeat value but I cannot figure out why it's timing out. Configuration is: Ubuntu 14.04, NGINX 1.8.1, RabbitMQ 3.6.0I'd appreciate your time and input !
RabbitMQ error timeout
I had a similar problem where Sidekiq was running but when I calledperform_asyncit didn't do anything except returntrue.The problem wasrspec-sidekiqwas added to my ":development, :test" group. I fixed the problem by movingrspec-sidekiqto the ":test" group only.
I am usingSidekiqfor my background jobs:I have a worker app/workers/data_import_worker.rbclass DataImportWorker include Sidekiq::Worker sidekiq_options retry: false def perform(job_id,file_name) begin #Some logic in it ..... end endCalled from a file lib/parse_excel.rbdef parse_raw_data #job_id and #filename are defined bfr DataImportWorker.perform_async(job_id,filename) endAs soon as i trigger it from my action the worker is not getting called.. Redis is running onlocalhost:6379Any idea why this must be happening. The Environment is Linux.
Sidekiq worker not getting triggered
I ran into the same thing. I had accidentally installed the nginx-extras package that is normally provided by Ubuntu, rather than the one provided by Phusion Passenger's repository. The Passenger package has Passenger compiled with Nginx as a module, while the other package does not.The solution is to add Phusion Passenger's apt repository, then install the nginx-extras package from it. The method of doing this differs slightly depending on your Linux distro and version so you should read the documentation first:https://www.phusionpassenger.com/library/install/nginx/apt_repo/If reading the documentation is a problem for you then you can try the commands I used to add the repository and install the nginx-extras package from it.sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 561F9B9CAC40B2F7 sudo apt-get install -y apt-transport-https ca-certificates sudo sh -c 'echo deb https://oss-binaries.phusionpassenger.com/apt/passenger trusty main > /etc/apt/sources.list.d/passenger.list' sudo apt-get update sudo apt-get install -y nginx-extras
I'm running into an error when I try to restart the server. I don't know how to fix this.deploy@user:~$ sudo nginx -s reload nginx: [emerg] unknown directive "passenger_root" in /etc/nginx/nginx.conf:66I added these lines to the nginx configuration file '/etc/nginx/nginx.conf'passenger_root /home/deploy/.rvm/gems/ruby-2.0.0-p353/gems/passenger-4.0.37; passenger_ruby /home/deploy/.rvm/gems/ruby-2.0.0-p353/wrappers/ruby;
Nginx unknown directive for passenger_root
I think you need to create this inside the location or server blockserver { server_name example.com; add_header Access-Control-Allow-Origin sub.example.com; # < this is the needed header # rest of the configuration }
I've got two domains:domain.com sub.domain.comdomain.com needs to make an ajax request to sub.domain.com. I realize that the browser will block this if the request is hardcoded to be sub.domain.com. I tried the following nginx conf:server { server_name domain.com; rewrite ^/api/(.*)$ http://sub.domain.com/api/$1; }However, I still get the following error in the browser (Chrome):No 'Access-Control-Allow-Origin' header is present on the requested resource.How can I set up nginx to instruct the browser to allow cross domain requests between domain.com and sub.domain.com?Thanks!
Set up nginx to allow cross-domain request for subdomain
I think youwillhave to set up a specific error page, however you can achieve what you're looking for if you do. Try this:location / { proxy_pass http://backend; proxy_intercept_errors on; error_page 502 503 504 =503 @proxyisdown; # always reply with 503 } location @proxyisdown { add_header Retry-After 500 always; index my_pretty_error_page.html; }If you work it this way you should be able to return the 503 (that's the=503part of theerror_pagedirective) and retry-after headers with the benefit that your visitors will receive a nicely formatted "oops, we're currently experiencing problems, try again in a few minutes" page rather than a blank "503 you don't really know what this means" page. :)
For SEO purposes, we would like to change the HTTP status code returned whenever the backend machine behind nginx goes down for some reason.We would like to change this to "503 Service Unavailable". As well as provide a Retry-After header to indicated to Google / Bing that the request should be retried in X number of seconds.Is this possible via nginx?I am not talking about a custom error page, but rather the status code returned in the header.
Is it possible to change the HTTP status code returned when proxy_pass gateway is down in nginx?
There is no such feature in official distribution of nginx. Beacause it may heavily reduce performance.Third party moduleshttp://wiki.nginx.org/3rdPartyModulesalso doesn't contain this feature.
I'm currently doing this in my nginx.conf:allow 1.2.3.4; deny;What I'd really like to do is this:allow my.domain.name; deny;I.e., I want nginx to do an A record lookup on my.domain.name at the time of the request, and if it matches the IP that the request is coming from, then allow it. I don't see any built-in mechanism to do this however. Anybody have a native way to do this before I start coding something custom?
how to "allow from hostname" in nginx config
Take a look at the following article,http://www.toofishes.net/blog/git-smart-http-transport-nginx/It provides a sample nginx config:http { ... server { listen 80; server_name git.mydomain.com; location ~ /git(/.*) { # fcgiwrap is set up to listen on this host:port fastcgi_pass localhost:9001; include fastcgi_params; fastcgi_param SCRIPT_FILENAME /usr/lib/git-core/git-http-backend; # export all repositories under GIT_PROJECT_ROOT fastcgi_param GIT_HTTP_EXPORT_ALL ""; fastcgi_param GIT_PROJECT_ROOT /srv/git; fastcgi_param PATH_INFO $1; } } }What this does is pass your repo which is located after /git in the url, to/usr/lib/git-core/git-http-backend. Example,http://git.mydomain.com/git/someappwould point to thesomeapprepository. This repo would be located in/srv/git/someappas defined in thefastcgi_paramofGIT_PROJECT_ROOTand can be changed to fit your server.This is very useful and you can applyHttpAuthBasicModuleto nginx to password protect your repo's access via HTTP.Edit:If you are missinggit-http-backend, you can install thegit-corepackage on Ubuntu/Debian or on RPM based platforms look atHow can git be installed on CENTOS 5.5?
Despite all the links I've found on how to configure git/nginx to get my repos, I can't make them work.I followed this tutorial,Git repository over HTTP WebDAV with nginx, but the user/password restriction doesnt' work. Anyone can clone the repository.I'm from a configuration using SVN + Apache + DAV_SVN, with a file for password (created with htpasswd), and a file for the authz. I'd like to do the same, using git+nginx. How's that possible ?Thanks for your help!
How to serve GIT through HTTP via NGINX with user/password?
If theproxy_passvalue doesn't contain variables, nginx will resolve domain names to IPs while loading the configuration and cache them until you restart/reload it. This is quite understandable from a performance point of view.But, in case of dynamic DNS record change, this may not be desired. So two options are available depending on the license you possess or not.Commercial version (Nginx+)In this case, use an upstream block and specify which domain name need to be resolved periodically using a specific resolver. Records TTL can be overriden usingvalid=timeparameter. Theresolveparameter of theserverdirective will force the DN to be resolved periodically.http { resolver X.X.X.X valid=5s; upstream dynamic { server foo.dnsalias.net resolve; } server { server_name www.example.com; location / { proxy_pass http://dynamic; ... } } }This feature was added in Nginx+ 1.5.12.Community version (Nginx)In that case, you will also need a custom resolver as in the previous solution. But to workaround the unavailable upstream solution, you need to use a variable in yourproxy_passdirective. That way nginx will use the resolver too, honoring the caching time specified with thevalidparameter. For instance, you can use the domain name as a variable :http { resolver X.X.X.X valid=5s; server { server_name www.example.com; set $dn "foo.dnsalias.net"; location / { proxy_pass http://$dn; ... } } }Then, you will likely need to add aproxy_redirectdirective to handle redirects.
I configured my Nginx as simple reverse proxy.I'm just using basic settinglocation / { proxy_pass foo.dnsalias.net; proxy_pass_header Set-Cookie; proxy_pass_header P3P; }The problem is that after some time (few days) the site behind nginx become unaccessible. Indead nginx try to call a bad ip (the site behind nginx is at my home behind my box and I'm a using a dyn-dns because my ip is not fixe). This dyn-dns is always valid (I can call my site directly) but for obscure reason Nginx get stuck with that..So as said, nginx just give me 504 Gateway Time-out after some time. It looks like the error come when my ip change at home. Here is a sample of error log:[error] ... upstream timed out (110: Connection timed out) while connecting to upstream, client: my.current.ip, server: myreverse.server.com, request: "GET /favicon.ico HTTP/1.1", upstream: "http://my.old .home.ip", host: "myreverse.server.com"So do you know why nginx is using ip instead of the DN ?
Error with IP and Nginx as reverse proxy
There's is a commandpassenger-config --rootwhich shows Passenger's root. All other config should be in the Apache or Nginx config file, which means insites-enabled/your_site.
Where is the Apache module installed for Phusion Passenger? I want to adjust some of the config values found in "Configuring Phusion Passenger".I don't know where this config file is. I've installed everything like the documentation says for Nginx.
Where is the Phusion Passenger config file?
Change nginx.conf to includesendfile on; client_max_body_size 20M; keepalive_timeout 0;See self answeruwsgi upstart on amazon linuxfor full example
I created an endpoint on my flask which generates a spreadsheet from a database query (remote db) and then sends it as a download in the browser. Flask doesn't throw any errors. Uwsgi doesn't complain.But when I check nginx's error.log I see a lot of2014/12/10 05:06:24 [error] 14084#0: *239436 upstream prematurely closed connection while reading response header from upstream, client: 34.34.34.34, server: me.com, request: "GET /download/export.csv HTTP/1.1", upstream: "uwsgi://0.0.0.0:5002", host: "me.com", referrer: "https://me.com/download/export.csv"I deploy the uwsgi likeuwsgi --socket 0.0.0.0:5002 --buffer-size=32768 --module server --callab appmy nginx config:server { listen 80; merge_slashes off; server_name me.com www.me.cpm; location / { try_files $uri @app; } location @app { include uwsgi_params; uwsgi_pass 0.0.0.0:5002; uwsgi_buffer_size 32k; uwsgi_buffers 8 32k; uwsgi_busy_buffers_size 32k; } } server { listen 443; merge_slashes off; server_name me.com www.me.com; location / { try_files $uri @app; } location @app { include uwsgi_params; uwsgi_pass 0.0.0.0:5002; uwsgi_buffer_size 32k; uwsgi_buffers 8 32k; uwsgi_busy_buffers_size 32k; } }Is this an nginx or uwsgi issue, or both?
uwsgi + nginx + flask: upstream prematurely closed
$http_is automatically created based on the request headers. You can see the same onhttps://nginx.org/en/docs/http/ngx_http_core_module.html#var_http_$http_namearbitrary request header field; the last part of a variable name is the field name converted to lower case with dashes replaced by underscores
I've seen it used in a lot of examples relating to CORS but where is the value of $http_origin set?I checked theNginx variablesbut there's no mention of it. And there's no mention inPHP FastCGI.
$http_origin in Nginx config files
Flaskadds a static routeto serve static files. When you're in production, you typically "short circuit" this route so that Nginx serves the files before the request ever gets to your app. Instead of adding this "short circuit", leave it out and let Flask handle the requests. Overwrite the static route with one that is wrapped by Flask-Login'slogin_required.from flask_login import login_required app.view_functions['static'] = login_required(app.send_static_file)This is typically overkill though, since you wanttruly staticfiles to be served no matter what so that pages look right to non-logged in users (otherwise the CSS wouldn't even be sent for the login page). Instead, "short circuit" the static folder to be served by Nginx, and define a route that will serve protected files from some other directory, such as the instance folder. Seeflask.send_from_directory.import os from flask import send_from_directory from flask_login import login_required @app.route('/protected/') @login_required def protected(filename): return send_from_directory( os.path.join(app.instance_path, 'protected'), filename )This will serve files from the directory "protected" in theinstance folderto logged in users only. Other restrictions could also be added, such as only allowing certain users access to certain files. Similar to the static path, you can generate a url to a file with:url_for('protected', filename='data/example.csv')
I want to restrict files to be available to logged in users, but otherwise return a 403 error or similar. For example a user should be able to view/download/static/data/example.csvonly if they're logged in.I know how to control the actual displaying of the files using Flask-Login if they're not logged in, but not how to block access to the file if they visit the link directly in their browser.
Restrict static file access to logged in users
I had the same problem. I updated nginx up to the current version (1.6.0). It seems to be working now.Server config:location /ipython { proxy_pass http://ipython_server; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Origin ""; }See:http://nginx.org/en/docs/http/websocket.html
I've gotnginxrunning handling all SSL stuff and already proxying/to aRedmineinstance and/cito aJenkinsinstance.Now I want to serve anIPythoninstance on/ipythonthrough that very samenginx.Innginx.confI've added:http { ... upstream ipython_server { server 127.0.0.1:5001; } server { listen 443 ssl default_server; ... # all SSL related stuff and the other proxy configs (Redmine+Jenkins) location /ipython { proxy_pass http://ipython_server; } } }In my.ipython/profile_nbserver/ipython_notebook_config.pyI've got:c.NotebookApp.base_project_url = '/ipython/' c.NotebookApp.base_kernel_url = '/ipython/' c.NotebookApp.port = 5001 c.NotebookApp.trust_xheaders = True c.NotebookApp.webapp_settings = {'static_url_prefix': '/ipython/static/'}Pointing my browser tohttps://myserver/ipythongives me the usual index page of all notebooks in the directory I launchedIPython.However, when I try to open one of the existing notebooks or create a new one, I'm getting the error:WebSocket connection failed:A WebSocket connection to could not be established. You will NOT be able to run code. Check your network connection or notebook server configuration.I've tried the same setup with the current stable (1.2.1, via pypi) and development (Git checkout of master) version ofIPython.I also tried adjusting thenginxconfig according tonginx reverse proxy websocketswith no avail.Due to an enforced policy I'm not able to allow connections to the server on other ports than 443.Does anybody haveIPythonrunning behind annginx?
How to configure IPython behind nginx in a subpath?
I'm using a glob for matching:file: /etc/nginx/conf.d/*Here's the corrected snippet:nginx: pkg.installed: - name: nginx service: - running - enable: True - restart: True - watch: - file: /etc/nginx/nginx.conf - file: /etc/nginx/conf.d/* - pkg: nginxAlso do note that salt can only watch other states that are already specified in your state file, so it will only watch files that are managed by salt itself.If this doesn't work for you, then try to refer the following link for a different solution:http://intothesaltmine.org/blog/html/2012/12/18/using_watch_with_file_recurse.html
I would like the nginx service to restart whenever any file in the/etc/nginx/conf.ddirectory is created or modified.There are a number of files in that directory, and rather than specifying particular files, I would like to watch for all changes.I've tried this:nginx: pkg.installed: - name: nginx service: - running - enable: True - restart: True - watch: - file: /etc/nginx/nginx.conf - file: /etc/nginx/conf.d - pkg: nginxbut the line- file: /etc/nginx/conf.dis not doing what I want.This is the error:ID: nginx Function: service.running Result: False Comment: The following requisites were not found: watch: file: /etc/nginx/conf.d Changes:I've also tried a number of variations including a trailing slash, but none of them work.What should- file: /etc/nginx/conf.d/be changed to?
SaltStack: In a watch statement, how do I specify a directory where all files should be watched?
You can send lots of requests to your server, using tools such as :absiegeJMeterThe first one, ab, will only allow you to send lots of a requests to a single URL -- which is great to benchmark a single script / page ; but doesn't reflect the real pattern of a user browsing your website(CSS/JS/images don't get loaded, for example).The second one, siege, will allow you to send requests to a list of URLs, specified in a text file -- building that list of URLs properly(there is a proxy for that)will get you some not too bad tests.And the third one, JMeter, will allow you to create more complex scenarios.That one is more complex, and you'll need a bit of time to use it -- but that's probably what will get you the best results.
So, I'd like to get more experience working with high-traffic websites, but unfortunately the Internet is not beating down the doors to my blog.How can I simulate tens/hundreds of hits per second on my blog and test its performance? I'm hosting my blog with an SSH account on a shared server.
How to simulate DDOS/Slashdotting?
According to thehomepageforppa:ondrej/nginx, here the PPA description:This branch follows latest NGINX Stable packages compiled against latest OpenSSL for HTTP/2 and TLS 1.3 support. BUGS&FEATURES: This PPA now has a issue tracker: https://deb.sury.org/#bug-reporting PLEASE READ: If you like my work and want to give me a little motivation, please consider donating: https://donate.sury.orgSo yes, same purpose asppa:ondrej/phpbut to install up to date Nginx (stable) versions.
I've juste addppa:ondrej/phpon my ubuntu server, and it prompt me the message below.Why am I advised to addppa:ondrej/nginx(stable) too? What's the exact purpose of this?For information I have already installed Nginxfrom the official doc.$ sudo add-apt-repository ppa:ondrej/php Note: PPA publishes dbgsym You need to add 'main/debug' component to install the ddebs, but apt update will print warning if the PPA has no ddebs Repository: 'deb http://ppa.launchpad.net/ondrej/php/ubuntu/ groovy main' Description: Co-installable PHP versions: PHP 5.6, PHP 7.x and most requested extensions are included. Only Supported Versions of PHP (http://php.net/supported-versions.php) for Supported Ubuntu Releases (https://wiki.ubuntu.com/Releases) are provided. Don't ask for end-of-life PHP versions or Ubuntu release, they won't be provided. Debian oldstable and stable packages are provided as well: https://deb.sury.org/#debian-dpa You can get more information about the packages at https://deb.sury.org IMPORTANT: The -backports is now required on older Ubuntu releases. BUGS&FEATURES: This PPA now has a issue tracker: https://deb.sury.org/#bug-reporting CAVEATS: 1. If you are using php-gearman, you need to add ppa:ondrej/pkg-gearman 2. If you are using apache2, you are advised to add ppa:ondrej/apache2 3. If you are using nginx, you are advised to add ppa:ondrej/nginx-mainline    or ppa:ondrej/nginx PLEASE READ: If you like my work and want to give me a little motivation, please consider donating regularly: https://donate.sury.org/ WARNING: add-apt-repository is broken with non-UTF-8 locales, see https://github.com/oerdnj/deb.sury.org/issues/56 for workaround: # LC_ALL=C.UTF-8 add-apt-repository ppa:ondrej/php More info: https://launchpad.net/~ondrej/+archive/ubuntu/php Adding repository. Press [ENTER] to continue or Ctrl-c to cancel.I don't know very well the Personal Package Archives (PPA), so I would appreciate some help about how it works.
What's the purpose of ppa:ondrej/nginx?
The simplest way - you need to generate all the content:Runnpm run generate.Go to thedistsubfolder of your project and copy all from there to some public hosting, like GitHub Pages.Though if you have some content depended from the user, you need to deploy it as a SPA:Changemodeinnuxt.config.jstospa.Runnpm run build.Deploy the createddist/folder to your static hostings like Surge, GitHub Pages or nginx.More details:https://nuxtjs.org/guide/commands#static-generated-deployment-pre-rendered-https://nuxtjs.org/faq/github-pages#how-to-deploy-on-github-pages-
At work, I got some little insight to nuxtjs development and I got very interested in it. So, I started developing on my own a little bit, but now, I'm stuck with my finished project.To develop, I spin up a local server with "npm run dev" in my CLI. This all works fine.But, how do I deploy my now finished project to run it in something like nginx (or are there better alternatives that run on an Windows Server environment) on my home server? I heard about "npm run build" into my CLI, but how is the procedure beyond that? And is that command even the right method?I'm absolutely a noob in this department. Could anybody teach me step by step what I have to do to go "in production"?Thank's very much in advance!MaxOf course, "npm run dev" isn't a viable option for production. It's only accessable from the machine the server is running on.
How to deploy a finished nuxt.js app to a webserver?
you need to uninstall one version of rack which is not required.Do this pleasegem uninstall rack -v 1.6.0Reference:How to force rack to work around the usual "You have already activated rack..." bug?
Similar toproblem with rack 1.3.2. You have already activated rack 1.3.2, but your Gemfile requires rack 1.2.3-- I'm experiencingYou have already activated rack 1.6.0, but your Gemfile requires rack 1.6.4when attempting to run Rails (4.2) in production with Puma and Nginx.bundle update rakenorrm Gemfile.lock && bundle installseem to help, the only solution I have so far is manually changingrack (1.6.4)torack (1.6.0)in Gemfile.lock.
You have already activated rack 1.6.0, but your Gemfile requires rack 1.6.4
I took a quick look at the manual and I think the closest you will find is passing fastcgi parameters:The request headers are transferred to the FastCGI-server in the form of parameters. In the applications and the scripts run from the FastCGI-server, these parameters are usually accessible in the form of environment variables. For example, the header "User-agent" is transferred as parameter HTTP_USER_AGENT. Besides the headers of the HTTP request, it is possible to transfer arbitrary parameters with the aid of directive fastcgi_param.http://wiki.nginx.org/HttpFcgiModule#Parameters.2C_transferred_to_FastCGI-server.fastcgi_paramsyntax: fastcgi_param parameter valuehttp://wiki.nginx.org/HttpFcgiModule#fastcgi_param
I use nginx with several fastcgi backends (php-cgi, mod-mono-fastcgi4). Now I need to sent an additional http header to the fastcgi backend, basically the same as proxy_set_header does when using nginx as reverse proxy. But to my findings, there is no such thing as fastcgi_set_header in nginx.Somebody got any ideas how to do this anyways? I dont want to use additional nginx modules as the solution muste be easily deployable on a wide range of customer systems.
Send additional header to FastCGI backend with nginx
This is how I serve my flask apps in Nginx:Run gunicorn daemonized using a socket:sudo gunicorn app:app --bind unix:/tmp/gunicorn_flask.sock -w 4 -DRelated nginx config:upstream flask_server { # swap the commented lines below to switch between socket and port server unix:/tmp/gunicorn_flask.sock fail_timeout=0; #server 127.0.0.1:5000 fail_timeout=0; } server { listen 80; server_name www.example.com; return 301 $scheme://example.com$request_uri; } server { listen 80; client_max_body_size 4G; server_name example.com; keepalive_timeout 5; # path for static files location /static { alias /path/to/static; autoindex on; expires max; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://flask_server; break; } } } }
I'm new at this and have only been using nginx to serve static files. I have now installed flask and gunicorn. If I rungunicorn -b 127.0.0.2:8000 hello:appand then wget it from the server it works well. If I try to access it from a browser, however, it returns a 404 error (I am running this on a server that hosts a wordpress site which is locatet at root).The flask app:from flask import Flask from werkzeug.contrib.fixers import ProxyFix app = Flask(__name__) @app.route('/') def hello(): return "Hello world!" app.wsgi_app = ProxyFix(app.wsgi_app) if __name__ == '__main__': app.run()And the relevant part of my nginx configuration:location /flask { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_\ for; proxy_pass http://127.0.0.2:8000; proxy_redirect off; }I hope this is all the relevant info. If not, do tell. Thanks!
Running a flask app with nginx and gunicorn
Per thewebSocket specification:Once the client's opening handshake has been sent, the client MUST wait for a response from the server before sending any further data. The client MUST validate the server's response as follows:If the status code received from the server is not 101, the client handles the response per HTTP [RFC2616] procedures. In particular, the client might perform authentication if it receives a 401 status code; the server might redirect the client using a 3xx status code (but clients are not required to follow them), etc.So, it's purely up to the client whether they want to support redirects or not and is clearly not something you can rely on unless you find in extensive testing that all relevant clients support it (which they apparently do not).You will either have to go with something like a server-side proxy or a client-side scheme to manually move the connection to another server.
I know that it is possible to pass requests through the reverse proxy (like Nginx, HAproxy and so on) but I need to redirect requests to another public server in the same domain suffix. I.e. fromwss://example.comtowss://ws1.example.com.Here is an example:I need to redirect requests from Nginx or Java. Is to possible to organize? Do I need to handle redirects on a client side or this code is enough?var socket = new WebSocket("wss://example.com"); socket.onopen = function() { alert("Connection established."); }; socket.onclose = function(event) { alert('Connection closed'); }; socket.onmessage = function(event) { alert("Data: " + event.data); }; socket.onerror = function(error) { alert("Error " + error.message); };
Is it possible to seamlessly redirect websockets?
This error comes when there is a heavy load on the server. First I had tried by increasing the value of worker_connections but it didn't work. Queue size for uWSGI is by default 100, so when more than 100 requests from Nginx to uWSGI is passed, queue get full and Nginx throws 502 to the client, to solve this increase the queue size of uWSGI. In uwsgi.ini file add "listen= {required queue size} ". In my case, I wrote, listen=200.But before doing it, you must check $ cat /proc/sys/net/core/somaxconn by default it's value is 128, so increase its vale by: $echo 200 > /proc/sys/net/core/somaxconnor $ sysctl -w net.core.somaxconn=200
I've django app host using nignx-uwsgi. Here is my uwsgi configuration:[uwsgi] master = true socket = /var/uwsgi/uwsgi.sock chmod-socket = 666 chdir = /home/ubuntu/test wsgi-file = /home/ubuntu/test/test/wsgi.py virtualenv = /home/ubuntu/virtual vacuum = true enable-threads = true daemonize= /home/ubuntu/uwsgi.logI'm getting error in nignx log2017/06/16 04:25:42 [error] 26129#0: *1141328 connect() to unix:///var/uwsgi/uwsgi.sock failed (11: Resource temporarily unavailable) while connecting to upstream, client: xxx.xxx.xx, server:and the site shows 502 bad gateway. I have to restart uwsgi to fix it. But the frequency of the error is increasing. Is there anyway to fix this.
Resource temporarily unavailable using uwsgi + nginx
server { server_name .laravel.dev; root /home/tamer/code/laravel/public; index index.php index.html; #browse folders if no index file autoindex on; # serve static files directly location ~* \.(jpg|jpeg|gif|css|png|js|ico|html)$ { access_log off; expires max; } # removes trailing slashes (prevents SEO duplicate content issues) if (!-d $request_filename) { rewrite ^/(.+)/$ /$1 permanent; } # enforce NO www if ($host ~* ^www\.(.*)) { set $host_without_www $1; rewrite ^/(.*)$ $scheme://$host_without_www/$1 permanent; } # canonicalize codeigniter url end points # if your default controller is something other than "welcome" you should change the following if ($request_uri ~* ^(/lobby(/index)?|/index(.php)?)/?$) { rewrite ^(.*)$ / permanent; } # removes trailing "index" from all controllers if ($request_uri ~* index/?$) { rewrite ^/(.*)/index/?$ /$1 permanent; } # unless the request is for a valid file (image, js, css, etc.), send to bootstrap if (!-e $request_filename) { rewrite ^/(.*)$ /index.php?/$1 last; break; } # catch all error_page 404 /index.php; location ~ \.php$ { try_files $uri =404; fastcgi_pass unix:/tmp/php.socket; fastcgi_index index.php; #include fastcgi_params; include /home/tamer/code/nginx/fastcgi_params; } access_log /home/tamer/code/laravel/storage/logs.access.log; error_log /home/tamer/code/laravel/storage/logs.error.log; }
I'm attempting to set up theLaravelPHP Framework to work withNginx. Here is my directory structure:/project /application /laravel /public index.php /legacy /index.php /stylesheets default.cssBasically what I have is a standardLaraveldownload w/ alegacyfolder thrown in which holds all of the files from my non-MVC project.I need Nginx to first check if the requested page/file exists inside of legacy, if it does then I want to use that. Otherwise, I want to fall back to Laravel'sindex.phpfile which is located inproject/public/.I'm no expert when it comes to Nginx configurations so any help that you can provide would be most appreciated.
Setting up Laravel with Nginx
You are right, if your nginx configuration (outside thelocationdirective) has noindexdirective, then thelocationdirective will never match and thefastcgi_indexdirective is useless.If you have a line like this on your configurationindex index.phpthen a request to/will create an internal redirect to/index.php, thelocationwill match and fastcgi will be called. php-fpm will need aSCRIPT_FILENAMEparameter that points to the file being executed. Normally, the configuration looks something like this:fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;$fastcgi_script_namecontains the name of the matched script, sofastcgi_indexis ignored.There is at least one instance wherefastcgi_indexis useful and used:when nginx and php-fpm are on different servers and nginx can't match the index.php file.
On many sites can be found this nginxlocationblock :location ~ \.php$ { fastcgi_pass 127.0.0.1:9000 fastcgi_index index.php ... }Given theofficial documentationoffastcgi_index, it seems like it is used when requests end with/. However, it doesn't match the regular expression of thelocationblock above? Am I missing something about thefastcgi_indexdirective?
What is fastcgi_index in nginx used for?
All the ideas I've had in the past:Sharing a docker volume from app to nginxYou can make a volume in the app'sDockefileand copy in the staticfiles when the container runs. Then share the volume with nginx container usingvolumes_from. This is kind of ugly and doesn't work at all if your appdepends_onnginx. I'd say this isdefinitely a no-goas it works terribly when scale up your app container.The idea of also mapping staticfiles from the host into the nginx container is also not optimal. You'll have an extra weird step to deal with them.Separate static containerBuild another nginx container serving only the static files on a different virtualhost.static.foo.bar.Use a CDNThere are tons of CDNs out there you can put your staticfiles and most frameworks have plugins for handling that. I have some projects doing this. Works great.Use uWSGIYou can serve staticfiles with uWSGI using--static-map. Seedocs. This is what I ended up doing as it was a cheap and easy... and friendly when it comes to scaling. Then you probably also need to usehttp-socketso uWSGI talks http instead.
Just to start off, I have seenthis. But he/she usesbuild, and I useimage.I have a docker-compose file that pulls an image that I have made previously onto my server.app: restart: always image: some-app-image:latestnginx configlocation /static/ { root /data/app/web_interface; <--- this exists in some-app-image container }Normally, I would have a volume mounted onto the app image that contains the static files.However, this is becoming redundant since the app container has the static files in itself.All the nginx container needs to do is "peer" into the app container and serve those static files. Like:location /static/ { root http://app:8000/web_interface; }orlocation /static/ { root app/web_interface; }Any chance there is a way to serve static files located in another container from a nginx container?
Serving static files with nginx located in another docker container
End result is that the /dev/stdout for the cron job was pointed to the different device./proc/self/fd/1 and should have been /proc/1/fd/1 because as docker only expects one process to be running this is the only stdout it monitors.So once I had modified the symlinks to point at /proc/1/fd/1 it should have worked however apparmor (on the host) was actually denying the requests (and getting permissions errors when echoing to /proc/1/fd/1) because of the default docker profile (which is automatically generated but can be modified with --security-opts).Once over the apparmor hurdle it all works!This said, after looking at what is required to be modified in apparmor to allow the required request I decided to use the mkfifo method as show below.DockerfileFROM ubuntu:latest ENV v="RAND-4123" # Run the wrapper script (to keep the container alive) ADD daemon.sh /usr/bin/daemon.sh RUN chmod +x /usr/bin/daemon.sh # Create the pseudo log file to point to stdout RUN mkfifo /var/log/stdout RUN mkfifo /var/log/stderr # Create a cronjob to echo into the logfile just created RUN echo '* * * * * root date 2>/var/log/stderr 1>/var/log/stdout' > /etc/crontab CMD "/usr/bin/daemon.sh"daemon.sh#!/bin/bash # Start cron cron tail -qf --follow=name --retry /var/log/stdout /var/log/stderr
I'm using the nginx method of symlinking linking to /dev/stdout for any log files that I want to appear in 'docker logs', however this is not working.I have tested this with a simple cronjob in /etc/crontab, if a symlink is present (pointing to /dev/stdout) it doesn't write anything (as far as I can tell), but if I delete the symlink and it writes to the file.Also if I echo into /dev/stdout it is echo'd back on the command line however it isn't found in 'docker logs'...Question: Should this work? (It seems to work with nginx). Else, how would I get logs from 'secondary' processes to appear in docker logs.For ref:Nginx Dockerfile showing the symlinking method:https://github.com/nginxinc/docker-nginx/blob/a8b6da8425c4a41a5dedb1fb52e429232a55ad41/DockerfileCreated an official bug report for this:https://github.com/docker/docker/issues/19616My Dockerfile:FROM ubuntu:trusty #FROM quay.io/letsencrypt/letsencrypt:latest # For testing ENV v="Fri Jan 22 10:08:39 EST 2016" # Setup the cronjob ADD crontab /etc/crontab RUN chmod 600 /etc/crontab # Setup letsencrypt logs RUN ln -sf /dev/stdout /var/log/letsencrypt.log # Setup cron logs RUN ln -sf /dev/stdout /var/log/cron.log RUN ln -sf /dev/stdout /var/log/syslog # Setup keepalive script ADD keepalive.sh /usr/bin/keepalive.sh RUN chmod +x /usr/bin/keepalive.sh ENTRYPOINT /usr/bin/keepalive.shThe crontab file:* * * * * root date >> /var/log/letsencrypt.logkeepalive.sh script#!/bin/bash # Start cron rsyslogd cron echo "Keepalive script running!" while true; do echo 'Sleeping for an hour...' sleep 10 done
Logging from multiprocess docker containers
Try:sudo aptitude purge nginx && sudo aptitude install nginxThis code will remove and reinstall Nginx
I'm trying to reinstall nginx, but I have thisnginx -t nginx: [alert] could not open error log file: open() "/var/log/nginx/error.log" failed (2: No such file or directory) 2015/01/25 16:18:01 [emerg] 1400#0: open() "/etc/nginx/nginx.conf" failed (2: No such file or directory) nginx: configuration file /etc/nginx/nginx.conf test failedHow to install and start nginx if I removed all the nginx folders?
How to reinstall nginx if I deleted /etc/nginx folder (Ubuntu 14.04)?
The culprit wasHeroku's rails_12factorgemRemoving that gem from the Gemfile, now the logs are working as expected.# group :production do # gem 'rails_12factor' # end
I have set up a rails 4 server on Ubuntu 12.04 using Capistrano, Nginx, Passenger, Postgres, Redis/ResqueEverything is working great, except that the production.log file is always empty.I have tried a variety of configuration changes in production.rb to no avail.It's definitely not a permissions issue, as the permissions on both the log dir and each of the logs are wide open (777)Can anyone hep me figure out how to get basic logging working?
production.log empty on Rails 4 / Capistrano / Passenger / Nginx server (digital ocean)
To answer an old question to help othersusing nginx 1.1.19 you can do the following:server { server_name ~^(?\w+)\.domainA\.com$; location / { rewrite ^ https://$subdomain.domainB.com$request_uri permanent; } }The subdomain before domainA.com is matched and stored in variable $subdomain which then can be used in the rewrite. This rewrites url like xxx.domainA.com to xxx.domainB.com with only one server directive.
The nginx documentation says that theserver_name directivesupports regular expressions. I've been banging my head against the wall trying to get even a trivial regex working.I wanthttp://subdomain.mydomain.comto redirect tohttp://mydomain.com/subdomainHere is my code.server { server_name "~^subdomain\.mydomain\.com$"; rewrite ^ http://mydomain.com/subdomain; }Also, potentially noteworthy. Further down in the nginx config file there is a rule:server { server_name *.mydomain.com ... }What am I doing wrong?UPDATE:It has been suggested that I not use regex for this... to offer a little more clarity: the trivial regex was simply for purposes of troubleshooting. The real regex will look more like...server { server_name "~^.*(cvg|cincinnati)\.fakeairport(app)?\.(org|com)$"; rewrite ^ http://fakeairport.com/cincinnati; } server { server_name "~^.*(lex|lexington)\.fakeairport(app)?\.(org|com)$"; rewrite ^ http://fakeairport.com/lexington; }So it would be preferable to use regex.
Redirecting a subdomain with a regular expression in nginx
changing ..access_log /var/log/nginx/access.log;to ..access_log /var/log/nginx/access.log main;fixed it.wheremainis the name of the log_format as defined at ..log_format main '$remote_addr - $remote_user xxx[$time_local]xxx ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent"';
Total NGINX beginner here.My logs currently look like:92.21.236.47 - - [08/Jan/2017:00:48:10 +0000] "GET / HTTP/1.1" 200 148 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0"When I add the following line in the default /etc/nginx/nginx.conflog_format main '$remote_addr - $remote_user xxx[$time_local]xxx ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent"'; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log;(the access_log and error_log lines already exist in the default config, I have put these here solely for context).I then restart NGINX with:systemctl restart nginxI now expect my logs to change and in particular to show the xxx literal values used .. xxx[$time_local]xxx .. but my change makes no difference.If I changelog_format maintolog_format combinedthen the server won't restart.
log_format in nginx.conf being ignored
Increase your buffer size in nginx configuration and restart nginx afterwards as suggestedhere.proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k;Further increase the fastcgi buffer in the php section of your configuration ( location ~ .php$ )fastcgi_buffer_size 128k; fastcgi_buffers 4 256k; fastcgi_busy_buffers_size 256k;Referenced answer to a question from a CodeIgniter userhere.
When I try to access a non-existing route or make a mistake inside a Twig template, instead of getting the Symfony error page with debug information, I get redirected to a default nginx 502 Bad Gateway.The log shows an interesting line:013/07/17 16:11:41 [error] 16952#0: *187 upstream sent too big header while reading response header from upstream, client: 127.0.0.1, server: ftwo.localhost, request: "GET /heasd HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "ftwo.localhost"Any ideas?
Nginx overwrites general symfony errors with 502 Bad Gateway
The default directory that static assets are served out of is/usr/share/nginx/html, not/var/wwwin theOfficial NGINX Docker image.With that said, you're also mapping your entire root directory and not the/public/folder where your folder contents live - unless of course you're running this from that directory on a pre-build image.You'll probably want something like:➜ docker run -p 80:80 -v $(pwd):/usr/share/nginx/html nginx
ProblemI have a Nginx container running in docker. It's configured to listen to porthttp://localhost:80. When I type the url to my browser I get the following...Welcome to nginx!If you see this page, the nginx web server is successfully installed and working. Further configuration is required.For online documentation and support please refer to nginx.org. Commercial support is available at nginx.com.Thank you for using nginx.Cont'd of ProblemI want nginx to serve my html files from my public directory. Please take a look at my project images...Project Images:Project directoryNginx Container RunningWhat I have doneRan the following docker command from my public directory...$ docker run -d --name chat-web -v $PWD:/var/www -p 80:80 nginxSearch for the location of nginx server from /usr/local/bin , /usr/private/var so that I can modify nginx.conf as described in the following postNGinx Default public www location?. I was unable to find the location of the nginx server.Thanks in advance for taking the time to answer my question. I really appreciate you.
How to Serve HTML Files from a Nginx Server Using Docker
I had the same issue. Confirmed there was a missing;at the end of a new added line inside the server block{...}.Ensure the curly braces and;areall in place.For example line like this will give error,server_name localhostAdding ';' to end like this will fix itserver_name localhost;
I'm new at nginx and Raspberry.I installed nginx usingsudo apt-get installAnd everything was fine at that point. The problem came when I tried to restart nginx, It threw this errorJob for nginx.service failed. See 'systemctl status ngins.service' and 'journaldtl -xn' for detailsAfter an investigation I found that the problem is the next error:unexpected end of file, expecting ";" or "}" in /etc/nginx/sites-enabled/default:20My default file is:# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples. ## server { #listen 80; ## listen for ipv4; this line is default and implied #listen [::]:80 default_server ipv6only=on; ## listen for ipv6 listen 80; server_name $domain_name; root /var/www; index index.html index.htm; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; # Make site accessible from http://localhost/ server_name localhost; location /I hope you can help me :)
nginx unexpected end of file, expecting ";" or "}" in /etc/nginx/sites-enabled/default:20 over Raspbian
Anything you can access as a variable in nginx config, you can log, including non-standard http headers, etc.The var you want to add is$server_portlog_format mycustomformat '$host $remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" $server_port'; access_log /var/log/nginx/access.log mycustomformat;
For testing purposes, I am using nginx to listen on multiple ports when I send distributed http requests. I can see the request be received by nginx - but I need to know which of its ports actually got it. I can't see any options in the logs to flag this.I guess an ugly alternative is to install multiple instances so their logs are separated, but there must be a better way than this...?
nginx: which port received the request?
The documentation for the status code 460 is updated for Application Load Balancers.This error occurs when the load balancer received a request from a client, but the client closed the connection with the load balancer before the idle timeout period elapses.Check whether the client timeout period is greater than the idle timeout period for the load balancer. Ensure that your target provides a response to the client before the client timeout period elapses, or increase the client timeout period to match the load balancer idle timeout, if the client supports this.You can read the full doc here:http://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-troubleshooting.html#http-460-issues
I'm seeing a concerning amount of460status codes in the logs of my Application Load Balancer. I don't see any patterns on these codes in regards to times, servers, or request URLs. According tothis forum post, the 460 means:The client has closed the connection with the ALB before the idle timeout has kicked in on either the front-end or the back-end connection.I can see the request making it to the backend server and the backend processes the request without issue and very quickly. Why are these errors happening? This ALB does a significant amount of traffic with 6-8 backend servers.Example ALB Log:https 2017-01-30T22:46:27.451363Z app/LOAD-BALANCER/bbab458ad0b80d X.X.X.X:55999 10.5.X.X:80 0.000 -1 -1 460 - 132 0 "GET https://www.website.com:443/app/page HTTP/1.1" "-" ECDHE-RSA-AES128-SHA TLSv1 arn:aws:elasticloadbalancing:us-west-2:743462462234:targetgroup/TARGET-GROUP/e6120e5adr245b79107e "Root=1-588fc23e-77aea5adf4534af3de09659d13a08"Example NGINX log from the backend:X.X.X.X 1485807955.048 www.website.com /app/page - GET 200 - 0.056 24 text/html; charset=UTF-8 -
Status Code 460 on Application Load Balancer
I just remove the whole server and installed everything again, that solved everything. Seems I got some old django ghost installation or somethingSorry and thanks!
I'm newbie with django, I'm trying to deploy my project on a production server but I'm getting this error:Error: No module named staticfilesWhen trying to start the server:python manage.py runfcgi host=127.0.0.1 port=8081 --settings=settingswith the fastCGI + nginxAny idea?Thanks!
Error: No module named staticfiles
You can setauth_basicconfiguration in theifclause like this:server { listen 443; auth_basic_user_file .htpasswd; ssl_client_certificate ca.cert; ssl_verify_client optional; ... location / { ... if ($ssl_client_verify = SUCCESS) { set $auth_basic off; } if ($ssl_client_verify != SUCCESS) { set $auth_basic Restricted; } auth_basic $auth_basic; } }Now, authentication falls back to HTTP Basic if no client certificate has been provided (or if validation failed).
I'm trying to set up Nginx server as follows:First, the server should check whether the user provides the client SSL certificate (viassl_client_certificate). If the SSL certificate is provided, then give access to the site,If the SSL certificate is NOT provided, then ask the user to enter a password and logs throughauth_basic.I was able to configure both the authentication methodat the same time. But this config is superfluous.To make check, whether the user provides its SSL certificate I try the config like this:18: if ($ssl_client_verify != SUCCESS) { 19: auth_basic "Please login"; 20: auth_basic_user_file .passfile; 21: }But Nginx returns an error:"auth_basic" directive is not allowed here in .../ssl.conf:19How can I to set the condition in this case?
Nginx config: how to use auth_basic authentication if ssl_client_certificate none provided?
SSL Labs doesn't assume thatSNIis available to the client, so it only tests the default virtual server.The problem could be that you don't have SSL session caching enabled on the default server. To enable it, you just need to add thatssl_session_cacheline to yourdefault_server. Alternatively, if you'd like that configuration the work across all of your nginx virtual servers (which I would recommend), you could move thessl_session_cacheline outside of the server declaration, so it applies to all of them.Here's the configuration I use:# All your server-wide SSL configuration # Enable SSL session caching for improved performance # http://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_session_cache ssl_session_cache shared:ssl_session_cache:10m; server { # All your normal virtual server configuration }Sources:I tested both options on my own server and SSL Labs loves it!This thread on the Nginx mailing list
SSLlabs still show the following message even after i added thessl_session_cacheSession resumption (caching) No (IDs assigned but not accepted)Here is my full configurationserver { listen 443 spdy; #Change to 443 when SSL is on ssl on; ssl_certificate /etc/ssl/domain.com_bundle.crt; ssl_certificate_key /etc/ssl/domain.com.key.nopass; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; #ssl_ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS; ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:!ADH:!AECDH:!MD5; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; ssl_buffer_size 8k; ssl_stapling on; ssl_stapling_verify on; ssl_trusted_certificate /etc/ssl/trustchain.crt; resolver 8.8.8.8 8.8.4.4; add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;"; #rest config goes here }
Session cache not detected in nginx
First php has to correctly flush everything :@ob_end_flush(); @flush();Then, I found two working solutions:1) Via Nginx configuration:fastcgi_buffering off;2) Via HTTP header in the php codeheader('X-Accel-Buffering: no');
We have code similar to this:In Apache, this would send each echo to the browser as it was output. In nginx/FastCGI however, this doesn't work due to the way nginx works (by default).Is it possible to make this work on nginx/FastCGI, and if so, how?
How to disable output buffering in nginx for PHP application
You can just use your VPS's ip in place of "sample.com":server { listen 80; server_name ; }If you haven't already, you may want to assign a static IP; I believe Digital Ocean gives you some free ones.
I'm working throughhttps://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-16-04. I've reached the end of the tut and started both uwsgi and nginx as directed. I have been able to get all steps working including uwsgi as far as I am aware.My test django site is in /home/deploy/sample as in the screenshotIf Isudo vim /etc/nginx/sites-available/sampleI see:server { listen 80; server_name sample.com www.sample.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/deploy/sample; } location / { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/sample.sock; } }Under "Install and Configure Nginx as a Reverse Proxy" the article states:Inside, we can start our server block by indicating the port number and domain name where our first project should be accessible. We'll assume that you have a domain name for each:I don't have a domain set up yet, but I wanted to open my VPS's ip address in my browser to see the test site.How can I make this happen?
Testing nginx without domain name
You can use a regular expression in theserver_nameto extract the part you need as a named capture. For example:server { listen 80; server_name ~^(?.+)\.example\.com$; return 301 http://example.com/$name$request_uri; }Seethis documentfor more.
I need a Guru's advice.On Nginx'sconffile, I would like to get the subdomain as a variable in order to redirect accesses as follow.ACCESS:http://userX.example.com/?hoo=barREDIRECT:http://example.com/userX/?hoo=barBut I getREDIRECT:http://example.com/userX.example.com/?hoo=barMy current_http.confsettings are like below. So obviously it works so.## default HTTP server { listen 80; server_name default_server; return 301 http://example.com/$host$request_uri; }Are there any vaiables or ways to do like below?## default HTTP server { listen 80; server_name default_server; return 301 http://example.com/$subdomain$request_uri; }I know if the subdomain part is limited it can be redirected, but I have to add them each time and I want it to keep as simple as possible.Is there any simple way to do so?[ENV]: CentOS:7.3.1611, nginx: nginx/1.13.3, *.example.com is targetted to the same server in NS settings.Conclusion (2017/12/13)Use a regular expression:server { listen 80; server_name ~^(?.+)\.example\.com$; return 301 http://example.com/$subdomain$request_uri; }Ref:Comment,Document
Nginx variable for subdomain?
I was curious about this too, so I dug into the source code and found this:if (hours >= 100) { snprintf(buffer, 10, "%7lluh ", hours); RichString_append(str, CRT_colors[LARGE_NUMBER], buffer); } else { if (hours) { snprintf(buffer, 10, "%2lluh", hours); RichString_append(str, CRT_colors[LARGE_NUMBER], buffer); snprintf(buffer, 10, "%02d:%02d ", minutes, seconds); } else { snprintf(buffer, 10, "%2d:%02d.%02d ", minutes, seconds, hundredths); } RichString_append(str, CRT_colors[DEFAULT_COLOR], buffer); }So, it looks like whenever the CPU time exceeds one hour, the hour portion is just highlighted in red (or whateverCRT_colors[LARGE_NUMBER]happens to be.)Notice that the time format changes as the time goes:4:33.42is minutes/seconds/millisconds18h26:41is hours/minutes/seconds101hwould be hours > 100
Below is my serverhtopdisplay. Thenginxprocess uses CPU time more then 18 hours, and is shown in red color, but CPU and memory all look OK. Is the value within the normal range?
When using htop command, do red values in the time+ column mean there's something wrong?
502 errors are generally caused by NGINX being unable to pass a request to "upstream", in this case your Node.js server (which is also what the error message suggests:"Connection refused"").It may be crashing and restarting, so check its logfiles to see what's causing the crashes.
I am getting 502 bad gateway error: when I check the nginx error log I find this:2017/05/06 02:36:04 [error] 48176#0: *135 connect() failed (111: Connection refused) while connecting to upstream, client: 10.163.XX.X, server: abc-def-ghi, request: "GET /favicon.ico HTTP/1.1", upstream: "https://127.0.0.1:5300/favicon.ico", host: "hostnname", referrer: "hostname-1I searched internet enough but could not find anything. One thing to note here is that, this intermittent error is coming only on a particular page.Could this be a code issue? or nginx configuration issue> Can anyone please help me here.Some of my nginx conf:upstream node_api_server { server localhost:5300 fail_timeout=0; } location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_read_timeout 5m; proxy_connect_timeout 5m; proxy_pass_header Set-Cookie; proxy_pass https://node_api_server; proxy_redirect off; proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; break; }
502 Bad Gateway error for my server running with Node JS on nginx proxy
Thetry_filesdirective isdocumented here.It specifically documents twofileelements:$uriand$uri/. The first tests for the presence of normal files and the second for the presence of directories.Theindexdirective is invoked as a consequence of processing a URI which points to a directory which contains a file matching one of the directives parameters.In the case oftry_files $uri /test.html;, the existence of a directory is not tested, and therefore the default action is taken.In the case oftry_files $uri $uri/ /test.html;, the existence of a directoryistested, and therefore the index action is taken.
The nginx.conf is as following:http { server { listen 8080; server_name example.com; root /tmp/test/example; location / { index index.html; try_files $uri /test.html; } } }When I accessexample.com:8080, it accesses the/tmp/test/example/test.html, not theindex.html.
Nginx: When the `index` and `try_files` in the same block, why the `try_files` will be processed, not the `index` directive?
uwsgi needs to be passed the scheme (http or https) used to serve the request in order to write the correct Location header.By default a bunch of settings are set in the/etc/nginx/uwsgi_paramsfile. Theinclude uwsgi_params;line in the config file is what load these.For whatever reason, though, the scheme is not one of these default settings. This can be fixed by adding:uwsgi_param UWSGI_SCHEME $scheme;to the nginx configuration after theinclude uwsgi_params;line, or by adding it to the/etc/nginx/uwsgi_paramsfile directly.
I have aflaskapp, hosted byuwsgi, withnginxas a reverse proxy to uwsgi, using the built-inuwsgi proxy module. Whenever I visit a page that redirects to another page, the Location header points to a non-HTTPS URL. For example:$ socat openssl:my-web-server:443 stdio GET / HTTP/1.0 Host: my-web-server HTTP/1.1 302 FOUND Server: nginx/1.0.4 [...] Location: http://my-web-server/loginMy nginx config looks like this:server { listen 80; listen 443 ssl; server_name my-web-server; charset utf-8; ssl_certificate /etc/nginx/certs/server.pem; ssl_certificate_key /etc/nginx/certs/server.key; location / { uwsgi_pass unix:/tmp/uwsgi.sock; include uwsgi_params; } }
unwanted HTTPS -> HTTP redirects with nginx + uwsgi + flask app
The first problem is you are specifying 100 max_children, that is awfully high for 2GB. I would drop it to 25 children. See my post here on how to optimise your php-fpm configuration for your setup:WARNING: [pool www] seems busy (you may need to increase pm.start_servers, or pm.min/max_spare_servers), spawningAlso, using unix sockets is slightly faster since it provides you direct network access without any TCP/IP overhead. On the down side, it is not as scalable as TCP/IP. Nginx will throw 502 errors when the sockets have been depleted. In such a case you can either tweak the OS settings to accommodate the larger connection pool or just switch to switch to TCP/IP.In your fastcgi conf change:fastcgi_pass unix:/var/run/php5-fpm.sock;to:fastcgi_pass 127.0.0.1:9000;Note that port 9000 is the default port set in php-fpm, if you have changed php-fpm to listen on another port then swap 9000 with that value. Make sure you restart both php-fpm and nginx.Now, if after all of this, you still cannot get it to work andfree -mreturns high memory usage, then it is time to add more ram to your server.
I have a 2GB VPS on DigitalOcean and I am hosting WordPress 3.9.1 under Debian 7 with NGINX, php-fpm and unix socket.It was working perfectly until last week it started showing a "502 bad gateway" error. I checked the logs and found that:php5-fpm log is showing pm.max_children was reached and nginx log is showing the following:[error] 3239#0: *15188 connect() to unix:/var/run/php5-fpm.sock failed (11: Resource temporarily unavailable) while connecting to upstream, client: xxx.xxx.xxx.xxx, server: my.domain, request: "POST /xmlrpc.php HTTP/1.0", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "xxx.xxx.xxx.xxx"I manually changed pm with different settings with no luck. I always restart the daemons after every change.pm settings are:pm = dynamic pm.max_children = 100 pm.start_servers = 10 pm.min_spare_servers = 10 pm.max_spare_servers = 10 pm.max_requests = 200www.confhas thelisten = /var/run/php5-fpm.sockenabled.Anyone with a similar experience?
Connect to unix:/var/run/php5-fpm.sock failed. What is wrong with my setup?
uWSGIcan be compiled on Windows only usingcygwin. There is no such thing asunamein normal Windows console, but it exists insidecygwin. If you're already in cygwin console, try to rununamecommand, if that exists, check ifos.uname()in python insidecygwinis also working.
Trying to install uwsgi according todocumentation.I'm getting the below error on Windows 7.What should I do?(uwsgi-tutorial) C:\Users\Home\Videos\uwsgi-tutorial\mysite>pip install uwsgi Collecting uwsgi Using cached uwsgi-2.0.11.1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 20, in File "c:\users\home\appdata\local\temp\pip-build-04g1m6\uwsgi\setup.py", line 3, in import uwsgiconfig as uc File "uwsgiconfig.py", line 8, in uwsgi_os = os.uname()[0] AttributeError: 'module' object has no attribute 'uname' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in c:\users\home\appdata\local\temp\pip-build-04g1m6\uwsgi
uwsgi installation error in windows 7
To verify that the problem isn't with the server, try running awget http://localhost/from your instance and see if you get the page you're expecting. If you do, it's probably firewall related.When you created your instance, you had to provide a security key (this is what you use to ssh into it) and a security group.You need to make sure that your security group has port 80 open (assuming you have nginx configured on port 80).If you have a new AWS account, and you're running your instance inside a VPC, you need to make sure your VPC has an internet gateway attached.
I'm trying to figure out how to set up Nginx on a micro-instance on AWS.The micro-instance is set up and running. I've associated an elastic IP to it. I SSH into it, make a new user runapt-get upgrade, thenapt-get install nginx. Nginx gets installed. Then I runsudo service nginx start. It looks like nginx is started. I can see the workers as running processes.So I try to access the server through the public IP ie. elastic IP via my browser in hope of seeing the 'Welcome to Nginx' screen. But all I get is the message that the server can't be found.I'm clueless on how to continue.
Setting up Nginx on a new micro-instance on AWS
That makes sense. I would define another virtual host (beta.example.com) with that different root folder and upon encountering cookie - do a rewriteYou can't set different roots for a domain conditionally, but you can redirect (rewrite) to another domain conditionallyThis guy's example helped me a bit agohttp://nicknotfound.com/2009/01/12/iphone-website-with-nginx/
I've seen some limited resources on checking for cookies with Nginx, but I couldn't really find the answer I was looking for, hopefully some of you Nginx masters can give me a hand.Essentially I have a vhost that I'd like to redirect to a different domain unless the user has a cookie, here is what I've created:server { listen 80; server_name example.com; if ($http_cookie ~* "dev_cookie" ) { root /home/deploy/apps/example/current/public; passenger_enabled on; rack_env production; break; } rewrite ^/(.*) http://beta.example.com/$1 permanent; }But it doesn't seem to work, I get the error:[emerg]: "root" directive is not allowed here in /opt/nginx/conf/nginx.conf:45I'm not sure how to proceed here, any ideas guys?
Nginx redirect if cookie present
For rewrite, the first argument is the match pattern and only applies to the path portion of the url, not the domain. In regular expressions,^matches the beginning of the input. For example,^/photos/.*$would match paths beginning in '/photos/'. By itself,^is a shortcut for all paths (since they all have a beginning).
A bit down onthisnginx config reference page you'll see:rewrite ^ http://example.com$request_uri? permanent;What is the meaning of^above?
in nginx config, what is the meaning of caret ^ by itself?
The only option for proxy is to have the certificate inside nginx. Another option would be to just TCP forward the connection outside of ngnix, but then you will not get any of the X-Real-IP, X-Forwarded-For etc stuff.
I have an Play 2.1.x application which signs itself using JKS. It's up, running and available atdomain.com:9443, I need to proxy it withnginx, as there will be more apps on the same machine, (therefore can't run it just on port443) I added the nginx config in hope thatproxy_passwithhttpswill allow me to just proxy it to clientupstream backend-secure { server 0.0.0.0:9443; } server { listen 443 ssl; server_name domain.com; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; location / { proxy_pass https://backend-secure; } }Unfortunately when trying to openhttps://domain.comin browser I only get log innginx/error.loglike:no "ssl_certificate" is defined in server listening on SSL port while SSL handshaking, client: 123.123.123.123, server: 0.0.0.0:443Is there a way to make it working or only option is using common way for nginx SSL + usinghttpbackend?Edit:It's EV, multidomain certificate if it matters.
How can i proxy to SSL backend without specifiyng cert files?
Ifbrew link openssl --forcegives you this message:Warning: Refusing to link: openssl Linking keg-only openssl means you may end up linking against the insecure, deprecated system OpenSSL while using the headers from Homebrew's openssl. Instead, pass the full include/library paths to your compiler e.g.:-I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/libTry this:$ brew doctor (now fix anything that it tells you to fix) $ brew update $ brew upgradeNow let's install it:$ brew install opensslAnd now we'll link it into our public area so you don't have to figure out the magic environment variable to set while building your favorite OpenSSL-backed library:$ cd /usr/local/include $ ln -s ../opt/openssl/include/openssl .All done! Enjoy
When I run:rvmsudo passenger-install-nginx-moduleon my Mac to install nginx, the terminal prints:Checking for OpenSSL development headers... Found: noBut I am certain I have openssl installed.which opensslreturns/usr/local/openssl/bin/openssland/usr/local/openssl/bin:is the first entry in my $PATH. My questions are:Are the OpenSSL development headers included with the regular openssl install through homebrew?If they aren't, where should I download them from?
Nginx Cannot Find OpenSSL Development Headers
The accepted answer routes everything throughindex.php.This will break certain script includes, thewp-adminscript being one of them.You can use:location /blog/ { index index.php; try_files $uri $uri/ /blog/index.php?$args; }
I has a site host on aNGINXserver which used to work fine to removeindex.phpin nginx site config usingtry_files.But now I am going to add a blog on it, where the URL will bewww.foo.com/blog, I can access the blog and useindex.php?p=.But, once I useprettypermalink with Nginx Helper,www.foo.com/blog/2013/07/bar, I get404.server { # don't forget to tell on which port this server listens listen 80; # listen on the www host server_name foo.com; # and redirect to the non-www host (declared below) return 301 $scheme://www.ultra-case.com$request_uri; } server { # listen 80 default_server deferred; # for Linux # listen 80 default_server accept_filter=httpready; # for FreeBSD listen 80; # The host name to respond to server_name www.foo.com; # Path for static files root /web/foo.com #index file index index.php; #Specify a charset charset utf-8; # Custom 404 page error_page 404 /404.html; # Uri Rewrite location /blog { index index.php; try_files $uri $uri/ /blog/index.php?$args; } location / { autoindex on; # This is cool because no php is touched for static content. # include tihe "?$args" part so non-default permalinks doesn't break when using query string try_files $uri $uri/ /index.php?$args; } location ~ \.php$ { #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini include fastcgi.conf; fastcgi_intercept_errors on; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; } # Include the component config parts for h5bp include conf/h5bp.conf; }
Nginx rewrite in subfolder (404)
It seemed to be a SELinux related problem. As suggestedin this questionI have tried usingsetsebool -P httpd_can_network_connect 1and everything works fine after that.
I have installed Jenkins CI on Cent OS 7 machine as well as NGinX and configured reverse proxy as outlined in thedocument. I can connect to Jenkins via port 8080, but cannot via port 80. I see the following error in/var/log/nginx/error.log:2014/09/22 22:12:35 [crit] 1639#0: *4 connect() to 127.0.0.1:8080 failed (13: Permission denied) while connecting to upstream, client: 10.10.81.212, server: 10.10.81.82, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8080/", host: "10.10.81.82"Does anyone has any idea what causes the problem?P.S. I used the similar setup on CentOS 6.4 and everything was fine.
NGinX cannot connect to Jenkins on CentOS 7
I'm not sure where you've seen it, but just using specifically$request_uriis certainly not going to magically make nginx resolve the domain names for you dynamically.Perhaps what was suggested was explicitly using the variables, such as$uri(which is a different variable), on the assumption that when the variables are in use, then the domain name is resolved individually each time, without any caching? I don't confirm or deny whether such assumption is correct, but the following will at least get rid of/afor you.location /a/ { rewrite ^/a/(.*) /$1 break; proxy_pass https://website.com/$uri$is_args$args; }(Note that if it's indeed implemented not to cache the domain name, then you might as well want to run a local resolver, otherwise, the extra latency and downtime of your hosting provider's DNS will immediately affect your site, not to mention the possible DNS query limits of their servers.)Perhaps a better solution would be to periodically restart nginx to automatically pick up the changes in DNS? E.g.,nginx -s reloadorkill -HUP? As explained inhttp://nginx.org/en/docs/beginners_guide.html#controlandhttp://nginx.org/en/docs/control.html#reconfiguration, nginx never stops processing any requests during reload, so it should be a safe operation; and it'll most likely result in DNS being flushed, too.
I'd like to proxy a request to another server using proxy_pass while removing the matched path prefix. I believe that one way of doing this is as follows;location /a/ { proxy_pass https://website.com/ }E.g. a request tohttp://localhost/a/b.htmlwould be proxied tohttps://website.com/b.html.As far as I am aware the issue with this in non-commercial versions on NGINX is that the DNS A record forwebsite.comwould be loaded and cached forever on startup. I've seen a technique to workaround this by using a variable such as$request_uriin the proxy_pass directive, thus forcing NGINX to re-resolve the DNS according to the TTL of the record.E.g.location /a/ { rewrite ^/a/(.*) /$1 break; proxy_pass https://website.com/$request_uri }Unfortunately, it seems that the above doesn't work as it seems to still pass the /a/ prefix to the upstream.Essentially all I want to achieve here is to proxy a request while removing the path prefix in such a way that DNS records are not cached forever.Thanks.
NGINX proxy_pass remove path prefix & resolve DNS
Yes. Gunicorn can serve your static too.If all else fails, let django do it for you (although, do this as a last resort before frustration.) To do that, you just have to add another url pattern, as follows:urlpatterns = patterns('', # ... the rest of your URLconf goes here ... ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)While django serving static is better than not serving it at all, it is worth delegating that to the servers optimized for the same like nginx.I'd recommend running nginx on a different port to start with, and change the django STATIC_URL setting to include the port (After you have confirmed that the port serves the statics). - Doing this is as simple as doing a simlink to the MEDIA_ROOT from the nginx folder.And if you are using nginx anyway, it is also good to proxy all requests using it and only pass the django request to the gunicorn. All this requires is the addition of aconffile that tells nginx accordingly.I can see how it can be confusing to those who are starting and trying to do all (proxy requests, serve static, configure nginx) at once. Try it one by one. Get the media from the gunicorn; Then serve it from nginx and then eventually have the nginx proxy too. But do this all before you have your app in production. This approach, I have seen increases understanding and decreases frustration.
I have tried just about every django + nginx tutorial on the web and I cannot get an image file to display on the screen. It's always the old story -404 PAGE NOT FOUND. The web page loads fine but django.png in my/static/folder does not. Not sure if it's a problem in settings.py or with nginx.I am so frustrated with it that I refuse to look at another "How to get nginx/django tutorial". If I deploy a website in the near future will Gunicorn suffice to run a Django site and serve static files simultaneously without using Apache or nginx? Is there a big benefit to having a reverse proxy in the first place?
Can Django run on Gunicorn alone (no Apache or nginx)?
Sinse 1.13 there is an "escape=none" parameter that turns off data escaping.http://nginx.org/en/docs/http/ngx_http_log_module.html#log_formatlog_format api_request_log escape=none '[$time_local] $request \n$request_body';
I am trying to log the request body of requests to my api and nginx is turning all quotes (and some other characters like spaces and tabs) into hexadecimal characters.Here is my log formatlog_format postdata '{"ts": "$time_iso8601", "status": $status, "req": "$uri", "meth": "$request_method", "body": "$request_body"}';Here is what gets logged{"ts": "2015-05-20T15:31:11-07:00", "status": 400, "req": "/v2/track", "meth": "POST", "body": {\x22id\x22:\x22user id\x22}}How can I prevent this so that the resulting log line is{"ts": "2015-05-20T15:31:11-07:00", "status": 400, "req": "/v2/track", "meth": "POST", "body": {"id":"user id"}}
nginx logging $request_body as hexadecimal
You are right in your understanding. Ingress has two parts a controller which implements Kubernetes ingress API interface for an automated and fast way to configure a reverse proxy such as Nginx or envoy.The other part is the reverse proxy itself such as Nginx, envoy.So when you deploy an ingress setup in Kubernetes it will deploy an ingress controller and a reverse proxy in your Kubernetes cluster.
Currently, I am studying Kubernetes and I came across the term Ingress object. I was wondering if there is a list of differences between the two as to me they seem like synonyms. To me it seems that an NGINX is a more functional ingress as it allows for instance video and image compression, pre-fetching and caching.On the other hand, Ingresses seem to overlap with NGINX' reverse proxies by providing load-balancing, traffic routing, TLS/SSL terminating. The only thing I see that an ingress may have compared to a NGINX/Envoy RP is that it is a "kubernetes API object".Does this mean that it consists of 2 parts - an interfacing one between the API and some actual reverse proxy? Meaning, is an "ingress" just a kubernetes term for a wrapper of an NGINX RP enforcing Kubernetes' API on it OR it is a totally separate type of server?Could you please list some list of the differences between the two?
What is the difference between an Ingress and a reverse proxy?
You can configure NGINX to pass the client's IP address with the following setting:location / { proxy_pass https://fotogena.co:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; # This line. proxy_connect_timeout 1000; proxy_send_timeout 1500; proxy_read_timeout 2000; }You can then use the HTTP headerX-Real-IPfromreq.headers["x-real-ip"].
I have a problem with nginx and node, because when i want get the ip of user with node, in my localhost works ok(no use nginx) but in my server dont work as it should. I was researching and see that the node no is the first that receive the ip, is nginx and after nginx send the request to node. then the ip that node receive is the my server and not user's ip. look the the configuration server nignx:location / { proxy_pass https://fotogena.co:8000; <-nginx send req to node proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_connect_timeout 1000; proxy_send_timeout 1500; proxy_read_timeout 2000; }i use "req.connection.remoteAddress" for know the ip of user and the console show me the ip of my server. somebody know how solve this problem?thanks :D-----------2016-04-20--------i can solved the problem, with this line on nginx file settingproxy_set_header X-Real-IP $remote_addr;and node.jsreq.headers['x-forwarded-for']
get ip user with nginx and node
I made a solution that works. I had it before posting this question but didn't realize I needed to restart nginx. Put the following inside your server block.rewrite ^(/mydirectory/)(.*)$ http://www.myotherdomain.com/$2 permanent;
I am very unfamiliar with nginx, as a forewarning, and also can't find any actual references on the regex system they use. So right now it's a black box to me.All I want to do is redirect a user trying to go to www.mydomain.com/mydirectory/X to www.myotherdomain.com/X .Seems like I should be using the rewrite command but the syntax of the regex is eluding me.Thanks in advance.
nginx - redirect a certain path to another domain
This sectionin docs describes, how to create a service file to automatically start your Asp.Net Core app.Create the service definition file:sudo nano /etc/systemd/system/kestrel-hellomvc.serviceThe following is an example service file for the app:[Unit] Description=Example .NET Web API App running on Ubuntu [Service] WorkingDirectory=/var/aspnetcore/hellomvc ExecStart=/usr/bin/dotnet /var/aspnetcore/hellomvc/hellomvc.dll Restart=always # Restart service after 10 seconds if the dotnet service crashes: RestartSec=10 SyslogIdentifier=dotnet-example User=www-data Environment=ASPNETCORE_ENVIRONMENT=Development [Install] WantedBy=multi-user.targetSave the file and enable the service.systemctl enable kestrel-hellomvc.serviceStart the service and verify that it's running.systemctl start kestrel-hellomvc.service systemctl status kestrel-hellomvc.serviceYou need to setWorkingDirectory- path to folder with your app andExecStart- with path to your app dll. By default this is enough.From now, your app willautomatically start on OS startupand will try torestart after crashes.
I would like to run my ASP.NET Core solution under linux with the result it runs on startup.From Microsoftdocs, there are 2 ways:ApacheandNginx.Both approaches involveproxy pass, e.g.Apache: ProxyPreserveHost On ProxyPass / http://127.0.0.1:5000/ ProxyPassReverse / http://127.0.0.1:5000/ ....Nginx:server { listen 80; server_name example.com *.example.com; location / { proxy_pass http://localhost:5000; ...Since Apache or Nginx only acts as proxy - do I get it right thatI have to manually start the dotnet app?I can't see the bit in the documentation where something could triggerdotnet runcommand against my WebApi project.Obviously, Apache or Nginx wouldn't handle triggering dotnet app - unless I've missed something.Is there a way to automatically start the app on OS startup?
run ASP.NET Core app under Linux on startup
We have solved the issue by adding the following to NGINX:proxy_http_version 1.1I guess NGINX proxies traffic by default with http version 1.0, but chunked transfer encoding is a http 1.1 feature.https://forum.nginx.org/read.php?2,247883,247906#msg-247906
We have tomcat with Jersey serving APIs behind NGINX. A new streaming API we have developed worked great when we call Tomcat directly, but started getting no response when calling it through NGINX.Looking at NGINX logs we got:upstream sent invalid chunked response while reading upstream
NGINX Error: upstream sent invalid chunked response while reading upstream
This is because you haven't set your secret key correctly. Double check your config/secrets.yml file: It should be something like this:production: secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>Then in your droplet, you can runbundle exec rake secretto get your secret key. There are options likedotenvwhich is a useful gem that loads the contents of a .env file into ENV.
I'm tyring to deploy a rails app to a digital ocean droplet and all seems to be configured ok but I get this error:An unhandled lowlevel error occurred. The application logs may have details.I'm not sure what to do as the logs are empty.Here's the nginx config:upstream puma { server unix:///home/yourcv.rocks/shared/tmp/sockets/yourcv.rocks-puma.sock; } server { listen 80 default_server deferred; server_name 127.0.0.1; root /home/yourcv.rocks/current/public; access_log /home/yourcv.rocks/current/log/nginx.access.log; error_log /home/yourcv.rocks/current/log/nginx.error.log info; location ^~ /assets/ { gzip_static on; expires max; add_header Cache-Control public; } try_files $uri/index.html $uri @puma; location @puma { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://puma; } error_page 500 502 503 504 /500.html; client_max_body_size 10M; keepalive_timeout 10; }Thank you! :)
An unhandled lowlevel error occurred. The application logs may have details
first,upgrade your nginx server to 1.3 or higher.second,my nginx conf works.you can follow my conf.server { listen 80; server_name jn.whattoc.com; location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://127.0.0.1:4050/; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; } }
I try to setup nodejs with nginx. But when the client try to connect it fails with...WebSocket connection to 'ws://www.mydomain.com/socket.io/1/websocket/KUv5G...' failed: Error during WebSocket handshake: 'Connection' header value is not 'Upgrade': keep-alive socket.io.js:2371So how to enable websocket comunication?my current nginx configupstream mynodejsapp { server 127.0.0.1:3000 max_fails=0 fail_timeout=10s weight=1; ip_hash; keepalive 512; } server { listen 80; listen [::]:80 default_server ipv6only=on; index index.html; server_name mydomain.com www.mydomain.com; keepalive_timeout 10; gzip on; gzip_http_version 1.1; gzip_vary on; gzip_comp_level 6; gzip_proxied any; gzip_buffers 16 8k; gzip_disable "MSIE [1-6]\.(?!.*SV1)"; location / { proxy_pass http://mynodejsapp; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_set_header X-NginX-Proxy true; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_cache_bypass $http_upgrade; proxy_http_version 1.1; proxy_redirect off; proxy_next_upstream error timeout http_500 http_502 http_503 http_504; proxy_connect_timeout 5s; proxy_read_timeout 20s; proxy_send_timeout 20s; proxy_buffers 8 32k; proxy_buffer_size 64k; } location ~ ^/(images/|img/|javascript/|js/|css/|stylesheets/|flash/|media/|static/|robots.txt|humans.txt|favicon.ico) { root /var/www/mynodejsapp; access_log off; expires 1h; } fastcgi_param APPLICATION_ENV production; }
WebSocket connection failed with nginx, nodejs and socket.io
This is because SocketIO uses/socket.iopath by default, so you need to configure Nginx so that it will proxy not only/noderequest, but/socket.iotoo:location ~ ^/(node|socket\.io) { #your proxy directives }(By the way, it looks like you have typos: you wroteproxypass, but the correct form isproxy_pass. The same goes to otherproxydirectives)You also need to perform one more edit in your NodeJS server file. Replace:app.get('/', function(req, res){with:app.get('/node', function(req, res){Now it should work.This is not the only solution. You could also changeSocketIO pathwith some changes in Nginx config, but the solution described above seems the simlest to me. Good luck!
I've followedthis tutorialto get Node.js working through Nginx on a two Ubuntu 14.04 servers via private networking (Node.js is on myappserver - accessible via private IP myprivatewebserver and publicly via mypublicappserver - and Nginx on mywebserver). Everything works fine til this point - I can access a node.js application on myprivateappserver:3000 proxied via Nginx by going tohttp://mywebserver/node.However, when I try and run up thechat applicationin socket.io on express.js, it works when I access it directly (http://mypublicappserver:3000) but, when I try and access it via my Nginx proxy (http://mywebserver/node), I get "Cannot GET /node" in the browser and in the firebug console " "NetworkError: 404 Not Found -http://mywebserver/node".If I curlhttp://myprivateappserver:3000from mywebserver, I get index.html from my socket.io application fine.My /etc/nginx/sites-available/default contains:location /node{ proxy_pass http://myprivateappserver:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; }My index.js is:var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); io.on('connection', function(socket){ console.log('a user connected'); socket.on('disconnect', function(){ console.log('user disconnected'); }); socket.on('chat message', function(msg){ io.emit('chat message', msg); }); }); http.listen(3000, function(){ console.log('listening on *:3000'); });and my index.html is: Socket.IO chat Send This is my first foray into nginx/node/express/socket (I'm normally an Apache/CakePHP person) so I may well be missing something very simple but would also be very grateful for any pointers on how to debug what's going wrong
"Cannot GET" on reverse proxy from Nginx to socket.io on express.js
You cannot useifhere, becauseif, being a part of the rewrite module, is evaluated at a very early stage of the request processing, way beforeproxy_passis called and the header is returned from the upstream server.One way to solve your problem is to usemapdirective. Variables defined withmapare evaluated only when they are used, which is exactly what you need here. Sketchily, your configuration in this case would look like this:# When the $custom_cache_control variable is being addressed # look up the value of the Cache-Control header held in # the $upstream_http_cache_control variable map $upstream_http_cache_control $custom_cache_control { # Set the $custom_cache_control variable with the original # response header from the upstream server if it consists # of at least one character (. is a regular expression) "~." $upstream_http_cache_control; # Otherwise set it with this value default "no-store, no-cache, private"; } server { ... location /api { proxy_pass $apiPath; # Prevent sending the original response header to the client # in order to avoid unnecessary duplication proxy_hide_header Cache-Control; # Evaluate and send the right header add_header Cache-Control $custom_cache_control; } ... }
I have a nginx proxy to a API server. The API sometimes sets the cache control header. If the API hasnt set the cache control I want nginx to override it.How do I do that?I think I want to do something like this, but it doesnt work.location /api { if ($sent_http_cache_control !~* "max-age=90") { add_header Cache-Control no-store; add_header Cache-Control no-cache; add_header Cache-Control private; } proxy_pass $apiPath; }
How to add headers in nginx only sometimes
You need to rewrite the uri without triggering a redirection as noted by usingbreak.Depending on the details of your set up, whether everything should go to the backend or whether Nginx should serve some requests such as static files, you will need either ...location /store { try_files $uri @store_site; } location /backoffice { try_files $uri @backoffice_site; } location @store_site { rewrite ^/store/(.*) /$1 break; include uwsgi_params; uwsgi_pass unix:/var/run/uwsgi/store_site.sock; } location @backoffice_site { rewrite ^/backoffice/(.*) /$1 break; include uwsgi_params; uwsgi_pass unix:/var/run/uwsgi/backoffice_site.sock; }... orlocation /store { rewrite ^/store/(.*) /$1 break; include uwsgi_params; uwsgi_pass unix:/var/run/uwsgi/store_site.sock; } location /backoffice { rewrite ^/backoffice/(.*) /$1 break; include uwsgi_params; uwsgi_pass unix:/var/run/uwsgi/backoffice_site.sock; }
This has been asked onSO beforebut the answers have not been generalized. So here goes.I have two different web apps. They were made to be on different servers at the root. But now they are going to be placed into subdirectories on the same server. The script below is sending the subdirectory along with the URI's to the scripts. This is a problem.old urls:http://store.example.com/items/1http://backoffice.example.com/accounts/1234new urls:http://www.example.com/store/items/1http://www.example.com/backoffice/accounts/12345The store site is seeing/store/items/1when it wants to just see/items/1. The same goes for the backoffice site.My attempt:location /store { try_files @store_site; } location /backoffice { try_files @backoffice_site; } location @store_site { include uwsgi_params; uwsgi_pass unix:/var/run/uwsgi/store_site.sock; proxy_set_header Host $host; } location @backoffice_site { include uwsgi_params; uwsgi_pass unix:/var/run/uwsgi/backoffice_site.sock; proxy_set_header Host $host; }Again, the store site is getting URLs with the/storeprefix and backoffice is getting/backoffice. Those sites were coded to not expect those prefixes. I need to remove the/storeand/backofficeprefix before sending to the actual site.Is this a rewrite rule thing?I tried this based onthis SO pageand it didn't work. I must not understand something about the syntax.location /store { rewrite ^/store/(.*) /$1; try_files $uri @store_site; }UpdateApparently, this works (addedbreak;) Is this a complete solution?location /store { rewrite ^/store/(.*) /$1 break; try_files $uri @store_site; }
How to remove a subdirectory from the url before passing to a script?
I tried this out on my VPS, and using thealiascommand worked for me:server { listen 80; server_name something.nateeagle.com; location /something { alias /home/neagle/something; index index.html index.htm; } }
I have files at/Users/me/myprojectand I want to serve them athttp://stuff.dev/somethingusing a simple nginx config. In the/Users/me/myprojectfolder is something like:index.html scripts/ app.js styles/ style.cssSo I really want to be able to accesshttp://stuff.dev/something,http://stuff.dev/something/scripts/app.jsetc.In my nginx conf I have this:server { listen 80; server_name stuff.dev; location /something { index index.html; root /Users/me/myproject; } }This doesn't work (I get a 404 if I try to go to those above URLs), however if I try the exact same set up but usinglocation / {instead oflocation /something {, it works fine. How can I serve this directory of files statically but at a path instead of at the location root? Do Ihaveto have the files in a folder called "something" like/Users/me/myproject/somethingfor this to work? If so is there a way around that?
How to serve a directory of static files at a certain location path with nginx?
The issue was the "http://database_server" it is a tcp stream so you need to just proxy_pass database_serveralso keep alive is not a directive that goes in a tcp upstream server
Question: Is it possible to set Nginx as a reverse proxy for a database? These are the flags I have at the moment and I believed that having the--with-streammodule was sufficient to use TCP streams to the database. Is this a PLUS feature?Nginx configuration options:--prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=%{_libdir}/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-http_ssl_module --with-http_realip_module --with-http_addition_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_stub_status_module --with-http_auth_request_module --with-threads --with-stream --with-stream_ssl_module --with-http_slice_module --with-mail --with-mail_ssl_module --with-file-aio --with-http_v2_module --with-cc-opt='-g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2' --with-ld-opt='-Wl,-z,relro -Wl,--as-needed' --with-ipv6Nginx configstream { include conf.d/streams/*.conf; }contents ofconf.d/streams/upstream.confupstream database_server { least_conn; keepalive 512; server 192.168.99.103:32778 max_fails=5 fail_timeout=30s weight=1; }Error message from Nginx2016/02/22 03:54:13 [emerg] 242#242: invalid host in upstream "http://database_server" in /etc/nginx/conf.d/streams/database_server.conf:9
TCP proxy to postgres database as an upstream server in nginx
You should use thedefault_typedirective :server { ... default_type text/html; location /images/png { default_type image/png; } location /images/jpg { default_type image/jpeg; } }
I have a server with nginx. And I have a lot of images - pngs and jpgs saved as files with no extension (like "123123123_321312").When I use tag "img" in html page, I get theese messages in console:Resource interpreted as Image but transferred with MIME type application/octet-stream: "http://xxxx/images/1350808948_997628". jquery.js:2 Resource interpreted as Image but transferred with MIME type application/octet-stream: "http://xxxx/images/1343808569_937350".Is there a way to make nginx add header with correct mimetype of the requested file?
How to specify mimetype of files with no extension in NGINX config?
server { listen 80; server_name example.com; rewrite ^/(.*) https://example.com/$1 permanent; } server { listen 443 ssl; server_name example.com; access_log /var/log/nginx/example.com_access.log combined; error_log /var/log/nginx/example.com_error.log error; ssl_certificate /etc/nginx/ssl/example-unified.crt; ssl_certificate_key /etc/nginx/ssl/example.key; location /static/ { alias /webapps/example/static/; } location /media/ { alias /webapps/example/media/; } location / { proxy_pass http://localhost:8000/; proxy_redirect off; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }This is basic nginx configuration that will work with SSL and will forward requests to uwsgi running on port 8000 (you can change this to socket if you want).For advanced SSL settings checkTHIS.
Does anyone have a working configuration for these four?- Django - uWSGI - Nginx - SSLThe main question is how to correctly set upSSLfor this? I've googled a lot, and still can't get it to work. I have a working set up forhttpwithunix sockets, but that's as far as I could get.There are some other answers posted, but they are mostly code snippets, and not a whole configuration.
Django + uWSGI + Nginx + SSL - request for working configuration (emphasis on SSL)
From the wiki:location = / { # matches the query / only. [ configuration A ] } location / { # matches any query, since all queries begin with /, but regular # expressions and any longer conventional blocks will be # matched first. [ configuration B ] }So, this will be matched first:location ~ \.php$ {}Even though assets are served out oflocation / {}Inside the php block you also want to secure against malicious uploads before passing to fastcgi:if ($uri ~* "^/uploads/") { return 404; }As you can see nginx works a little bit differently than you might expect.
I'm trying to optimize my 'location' directives and cannot find a good way of determining if a specific location match is even attempted. Usingechoinside the location block doesn't help here.The NGINX ngx_http_core_module documentationis somewhat confusing.To use regular expressions, you must use a prefix:~For case sensitive matching~*For case insensitive matchingHow the match is performed:Directives with the=prefix that match the query exactly. If found, searching stops.All remaining directives with conventional strings. If this match used the^~prefix, searching stops.Regular expressions, in the order they are defined in the configuration file.If #3 yielded a match, that result is used. Otherwise, the match from #2 is used.Number 2 here says "conventional strings" but then says it can be used with the^~prefix. Doesn't~imply a RegExp? If not, how does it determine what is an isn't a RegExp?Specifically, I want the following:Serve anything out of literal/assetsdirectly. STOP SEARCH.Serve anything matching RegExp\.php$|/$via fast-CGI STOP SEARCH.Serve everything else directly via literal/This way, there is only a/match attempt for non-dynamic files served from outside of assets.I have:location ^~ /assets {} # search-terminating literal? or regex? location ~ \.php$|/$ {} location / {} # is this match always attempted?From the document, it looks as though the actual order would be 1-3-2, always running the literal/match. Yes, this optimization won't make any difference for real performance, but I just want to clear up some ambiguity.
How to control NGINX 'Location' directive matching order?
If you use "pm2 delete {appname}" to delete the last apppm2 delete appwhen you runpm2 saveIt will show[PM2] Saving current process list... [PM2] Nothing to save !!! [PM2] In this case we keep old dump file. To clear dump file you can delete it manually !Which means, actually, the last app information is still not deleted.The solution is to create a new dump file.pm2 cleardumpThen, the app will be deleted permanently.You can check the pm2 file to see what's actually saved into dump file./home/ubuntu/.pm2/dump.pm2
I have a pm2 process namedappthat was used to test the configuration.I noticedappwas starting when the system rebooted, and it was causing errors with the real application.I ran:pm2 delete appthen I ran:pm2 listand it didn't showapp.When I reboot my system, the app is still there and it is running. I attempted to find information on where the config file is online, and there is no information other than creating a template config file. Where should the config file that pm2 reads on startup be located on an Ubuntu system, or why isn't delete working as I intend? Is there another method or command I can use to remove a pm2 process or am I looking at this incorrectly?
PM2 deleted process runs on startup
As I don't allow anonymous access, it turns out I needed to create a specific user for GitHub pushes and to grant it Overall read, Job create and Job read. It was also necessary to bundle the authentication into the webhook URL, like so:https://foo:[email protected]/github-webhook/
I have a GitHub repository which I would like to have notify Jenkins of new commits via a post-receive hook. I've installed the GitHub plugin into Jenkins and have allowed for Jenkins to manage it's own hook URLs. The project has the correct git repository URL and is instructed to "Build when a change is pushed to GitHub". When I have GitHub send a test payload I find this in the nginx webserver that front's Jenkins:207.97.227.233 - - [15/Sep/2011:07:36:51 +0000] "POST /github-webhook/ HTTP/1.1" 403 561 "-" "-"I was running SSL so I disabled it to no effect. Do I need to provide special permissions to an anonymous user in the permissions matrix?Please forgive the lack of configuration files: I'm happy to share those that might exist but I don't know what might be useful to share.
Jenkins and GitHub webhook: HTTP 403
To come back to this post. Unfortunatly I found the problem. Chrome does not support this option, therefore Chrome gives me the error that the iframe redirected me to many times.However the option works on Firefox (More information here:https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options).
I am using Nextcloud (on Nginx) for a while now and I want to iframe it for another website. However the header does not accept my directives.I changed the header option in /var/www/nextcloud/lib/private/legacy/response.php into the following:header('X-Frame-Options: ALLOW-FROM https://example.com');However when I make an example webpage with an iframe it gives me the following error:Invalid 'X-Frame-Options' header encountered when loading 'https://nextcloud.example.com/apps/files/': 'ALLOW-FROM https://example.com' is not a recognized directive. The header will be ignored.Does anyone have an idea why this does not work?
X-Frame-Options header is not a recognized directive
To change this behavior, you'll have to change the logrotate file of nginx. This file is probably located in /etc/logrotate.d. For achieving what you're trying to do, put the directivesweeklyandrotate 30inside the file corresponding to nginx. After that, use the following command to ensure the changes take effect:logrotate /etc/logrotate.d/nginx-config-file
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be abouta specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic onanother Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.Closed1 year ago.The community reviewed whether to reopen this question1 year agoand left it closed:Original close reason(s) were not resolvedImprove this questionI want to keep the nginx logs of the lsat 30 days. The default configuration is 15 days, as the image shows.I would like to keep the last 30 days instead.Here are the looging settings of nginx:## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log;But it doesn't say anything about "how oft" it should be taken.I'm not a nginx expert at all, so I don't know how/where I can change that configuration.Maybe someone there needed to do the same and want to help me.
keep the nginx logs of the last 30 days [closed]
When you usespring-session, e.g. to persist your session in reddis, this is indeed done automatically. The cookie is than created byorg.springframework.session.web.http.CookieHttpSessionStrategywhich inCookieHttpSessionStrategy#createSessionCookiechecks if the request comes via HTTPS and sets secure accordingly:sessionCookie.setSecure(request.isSecure());If you donotuse spring-session, you can configure secure cookies using aServletContextInitializer. Use aapplication property, to set it to true/false depending on a profile.@Bean public ServletContextInitializer servletContextInitializer(@Value("${secure.cookie}") boolean secure) { return new ServletContextInitializer() { @Override public void onStartup(ServletContext servletContext) throws ServletException { servletContext.getSessionCookieConfig().setSecure(secure); } }; }application.properties (used in dev when profile 'prod' is not active):secure.cookie=falseapplication-prod.properties (only used when profile 'prod' is active, overwrites value in application.properties):secure.cookie=falsestart your application on the prod server with :--spring.profiles.active=prodSounds like some effort, if you have not worked with profiles so far, but you will most likely need a profile for prod environment anyway, so its really worth it.
I have a tomcat application server that is behind a nginx. SSL terminates on the nginx. The Spring web-mvc application that is deployed on the tomcat should set the secure flag on the JSESSIONID. It would be cool if spring has some automatic detection for this so I don't get bothered during development because I don't have SSL there.Is there a way to tell spring to set the flag automatically?I use JavaConfig to setup the application and use Maven to create a deployable war-file.I have checked this already, but this looks somehow ugly and static:set 'secure' flag to JSESSION id cookie
Add secure flag to JSESSIONID cookie in spring automatically
Short answer:No, you can't.Long answer:You can't get body of a response returned toauth_request. You can get a header returned in the response though, using theauth_request_setdirective:location / { auth_request /auth; auth_request_set $auth_foo $upstream_http_foo; proxy_pass ... proxy_set_body $auth_foo; }The above configuration will set the$auth_foovariable to the value ofFooheader of an auth subrequest.
I am using auth module for nginx. (http://nginx.org/en/docs/http/ngx_http_auth_request_module.html) Is it possible somehow to store the response from the /auth, so I can send it as a request body to another endpoint.location /private/ { auth_request /auth; proxy_pass ... proxy_set_body 'Here I want to put /auth response. How?'; } location = /auth { proxy_pass ... }
Nginx: Is it possible to get response retuned from auth_request
I found the answer to my my question in a django bug report.proxy_set_header Host $http_host;has to be replaced with:proxy_set_header Host $host;to make nginx pass the correct headers from that on instead of the gunicorn socket the requested page was in the django alerts.
After I deployed my Django App last night I got tons of strange Emails saying:ERROR: Invalid HTTP_HOST header: '/webapps/example_com/run/gunicorn.sockI'm sure this is somehow related to the following nginx config:upstream example_app_server { server unix:/webapps/example_com/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name example.com; client_max_body_size 4G; access_log /webapps/example_com/logs/nginx-access.log; error_log /webapps/example_com/logs/nginx-error.log; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://example_app_server; break; } } }
ERROR: Invalid HTTP_HOST header: '/webapps/../gunicorn.sock'
You could use the$schemevariable:location /api/v1/json { # Various proxy config directives proxy_pass $scheme://your-host }From thedocs:$scheme request scheme, "http" or "https"Which would then use the same protocol as the original request.
I have a section in my NGINX config file that usesproxy_passto redirect API traffic to upstream servers. I have thelocations in oneserverblock that serves both http and https requests:server { listen 80; listen [::]:80; listen 443 ssl; listen [::]:443 ssl; server_name mysite.local; # Valid TLD in productionI then havelocationblocks to define my API gateways:location /api/v1/json { # Various proxy config directives proxy_pass http://upstream;My question is: would it be possible to drophttp://and pass requests to my upstream servers depending on the protocol without splitting myserverblock? Something like HTML/JavaScript//mysite.localrequests.
NGINX proxy_pass same protocol (http/https)
server { listen 80; server_name sub.example.com; location / { proxy_pass https://123.12.12.12/path; } }Thats how it works. If proxy_pass contains locations part - current location will be replaced to specified.http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_passBut it's help only for http request and http redirects. If application create html with linkshttps://123.12.12.12- it's still unchanged. In this case you can try ngx_http_sub_module.
There's a few similar questions on SO, but none exactly mine, and I've had no luck trying to adapt their answers so far.I want to map the URLhttp://sub.example.comtohttps://123.12.12.12/path, such that the browser still shows the URLhttp://sub.example.com.My Nginx config file looks like,server { listen 80; server_name sub.example.com; location / { proxy_pass https://123.12.12.12; rewrite ^/$ /path last; } }The routing works here, but the URL displayed ishttp://sub.example.com/path. How do I make it display onlyhttp://sub.example.com?
Nginx URL masking to a different domain
Addinginclude proxy_paramsfixed it for me.location / { proxy_pass http://...; include proxy_params; }
I am having a problem with the redirect(url_for) function in my flask app.Any redirect(url_for("index")) line redirects the application fromdomain.com/apptoip-addr/app, where theip-addris my own client machines ip, not the server's.This has gotten me very confused, and I don't know where exactly the issue occurs, as it only happens on the server and not on any local testing.Details:I am using the reverse proxy setup found herehttp://flask.pocoo.org/snippets/35/. My nginx config is setup like solocation /app { proxy_set_header X-Script-Name /app; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Host $proxy_add_x_forwarded_for; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_connect_timeout 60; proxy_read_timeout 60; proxy_pass http://localhost:8000/; }I have gunicorn running my flask app as a upstart task. Any hints?EDIT:So I dug around a bit and found that the this git report had similar issues,https://github.com/omab/django-social-auth/issues/157.Nginx - Gunicorn serving to Nginx via localhost (127.0.0.1:1234). Unfortunately, when I authenticate with social platforms, the redirect URL social-auth is sending them to is 127.0.0.1:1234/twitter/complete, which obviously can't be resolved by the client's browser.It seems my Flask app is not getting the memo to update its redirect routes.
Flask redirect(url_for) error with gunricorn + nginx
The most likely cause for this problem is that the server usesServer Name Indicationto choose which certificate to send. If the client doesn't support SNI, the server cannot choose which certificate to send during the SSL/TLS handshake (before any HTTP traffic is sent). SNI is required when you want to use multiple certificates on the same IP address and port, but not all clients support it (notoriously, IE on any version of Windows XP, and a number of mobile browsers).You're also visibly using the Apache HTTP Client library (notHttpsURLConnection, for whichthere can be SNI support with some Android versions. Support for SNI in the Apache HTTP Client libraryis quite recent, and certainly hasn't made it into the Android stack.You may findthe workaround described in this articleuseful (although it seems only to work for Android 4.2+).Another two options would be:to use a distinct IP address for each host (so as not to need SNI), if you're in control of server, orto use another HTTP Client library (e.g.HttpsURLConnection).
I have two domains:foo.netandbar.com. They both have SSL certificates, and they work well in all desktop and mobile browsers. They are hosted on the same server configured with nginx.However, when I make a request to a domain from within a native android app, it somehow gets the certificate from the wrong domain! This results in an IO Exception:request = new HttpPost("https://foo.net/api/v1/baz"); request.setHeader("Authorization", "user:pass"); response = httpClient.execute(request);...javax.net.ssl.SSLException: hostname in certificate didn't match: != OR OR What would cause android/java to try using the certificate frombar.comwhen every other measure seems to indicate that the server is correctly configured? Nothing appears in the nginx access or error log. There is no mention ofbar.comanywhere in my android project.Edit: I'm not sure why, but it appears that the server is using the certificate forbar.comfor the server IPhttps://198.245.xx.xxx
Why does android get the wrong ssl certificate? (two domains, one server)
The issue is probably that you never actually restarted php-fpm. I had issues with this as well, apparently theres a bunch of different ways to restart php-fpm, and some of them dont work for certain environments.https://serverfault.com/questions/189940/how-do-you-restart-php-fpm/506951Try those and see if they reload it.
I've made changes tomax_upload_sizein/etc/php5/fpm/php.iniand restarted both nginx and php5-fpm services.phpinfo()states that/etc/php5/fpm/php.iniis being loaded but after reloading/restartinb both services,max_upload_sizeremains unchanged.Question:A server reboot solved the problem. Why is a reboot required? Did I miss out anything when restarting the services?
Reloading nginx & php5-fpm does not update changes to php.ini
I figured it out, since I was using SSL, I needed to make sure it was https. Here is my final config:upstream app_nodejs { server 127.0.0.1:3000; } server { #listen 80 is default server_name www.mydomain.com; return 301 $scheme://mydomain.com$request_uri; } server { listen 80; listen [::]:80; listen 443 default ssl; ssl on; ssl_certificate /root/certs/bundle.crt; ssl_certificate_key /root/certs/mydomain.key; server_name mydomain.com; if ($ssl_protocol = "") { rewrite ^ https://$server_name$request_uri? permanent; } location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass https://app_nodejs; proxy_redirect off; } }
I'm trying to setup nginx so that it pull the app running on port 3000.When I visit mydomain.com:3000, the app works. I want it to run without the port.I have nginx setup and it's working properly. I have an SSL cert setup and it's working properly (I'm able to see the nginx start page with SSL) I have the www redirect working properly.The part I want to do now is take what is running on port 3000 and have it run on port 80.Here is my config file:upstream myapp { server 127.0.0.1:3000; } server { #listen 80 is default server_name www.mydomain.com; return 301 $scheme://mydomain.com$request_uri; } server { listen 80; listen [::]:80; listen 443 default ssl; ssl on; ssl_certificate /root/certs/bundle.crt; ssl_certificate_key /root/certs/mydomain.key; server_name mydomain.com; if ($ssl_protocol = "") { rewrite ^ https://$server_name$request_uri? permanent; } location / { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; try_files @node $uri.html; } location @node { proxy_pass https://myapp; } }When I visit the page with this setup, I get a 500 internal server error. What am I doing wrong?
nginx config for express app running on port 3000
I cannot spot the error in your configuration file; I'm an nginx-newbie as well.But here is my full nginx.conf config file which redirectshttp://myhost/cabaret/foo/bartohttp://myhost:8085/foo/bar:user www-data; worker_processes 1; error_log /var/log/nginx/error.log; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; access_log /var/log/nginx/access.log; sendfile on; keepalive_timeout 65; tcp_nodelay on; server { listen *:80; ## listen for ipv4 access_log /var/log/nginx/localhost.access.log; location /cabaret { rewrite /cabaret(.*) $1 break; proxy_pass http://127.0.0.1:8085; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } }It is not perfect, because it will not work withhttp://myhost/cabaret, only if a slash followscarabetlike inhttp://myhost/cabaret/orhttp://myhost/cabaret/foo/bar.
I have running nginx on my server ansel.ms and a node.js app on ansel.ms:46156.I want to setup nginx so it redirects everything fromansel.ms/rhythmtoansel.ms:46156. ansel.ms/rhythm/sub/pathshould becomeansel.ms:46156/sub/pathThis is my file in sites-available:upstream rhythm { server ansel.ms:46156; } server { listen 80; server_name ansel.ms www.ansel.ms; access_log /srv/www/ansel.ms/logs/access.log; error_log /srv/www/ansel.ms/logs/error.log; location / { root /srv/www/ansel.ms/public_html; index index.html index.htm; } location ~ \.php$ { include fastcgi_params; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /srv/www/ansel.ms/public_html$fastcgi_script_name; } location /rhythm{ proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-NginX-Proxy true; proxy_pass http://rhythm; proxy_redirect off; } }I do not really understand deeply what this does (the proxy_set_header stuff), I only copied & pasted it from several sources.It doesn't work.Can you give me a hint what to change so it does what I described above? Thank you!
How to redirect address.com/foo/bar to address.com:port/bar with nginx?
Redirect request then you can return status code easily:server { error_page 500 502 503 504 @blackhole; location @blackhole { return 444; } }
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be abouta specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic onanother Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.Closed1 year ago.The community reviewed whether to reopen this question1 year agoand left it closed:Original close reason(s) were not resolvedImprove this questionI always use "return 444" in the nginx config to stop crawlers that access my servers directly via IP or via the wrong hostname. It just closes the connection. Perfect.Now I want to use this response instead of the standard 404.html pages that nginx throws, but I fail at configuring.error_page 500 502 503 504 /custom_50x.html;This works fine, but I can't "return 444" like here:server { listen 80; server_name ""; return 444; }Does anybody know a way to combine these two?
HTTP 444 (No Response) instead of 404, 403 error pages? [closed]
Yes.If you just haveproxy_cache_bypassset true on pages you don't want cached (eg. logged in users) then they will still be saved into the cache and served to people who should get cached pages (eg. non logged in users).But setting bothproxy_cache_bypassandproxy_no_cacheto true means that those users neither receive nor contribute to the cache.
Here's the documentation:proxy_cache_bypassDefines conditions under which the response will not be taken from a cache. If at least one value of the string parameters is not empty and is not equal to “0” then the response will not be taken from the cache:proxy_cache_bypass $cookie_nocache $arg_nocache$arg_comment;proxy_cache_bypass $http_pragma $http_authorization;Can be used along with the proxy_no_cache directive.proxy_no_cacheDefines conditions under which the response will not be saved to a cache. If at least one value of the string parameters is not empty and is not equal to “0” then the response will not be saved:proxy_no_cache $cookie_nocache $arg_nocache$arg_comment;proxy_no_cache $http_pragma $http_authorization;Can be used along with the proxy_cache_bypass directive.Does that mean if I want to totally exclude something in cache, I should set bothproxy_no_cacheandproxy_cache_bypass? Is it OK if I only setproxy_cache_bypass?
Nginx proxy_no_cache and proxy_cache_bypass
Edit yournginx.conffile, add alocationinto yourserver {}block:location = /lua { default_type text/plain; content_by_lua ' if jit then ngx.say(jit.version) else ngx.say("Not LuaJIT!") end '; }Then start your nginx server and then access /lua in curl or in your favorite web browser. If you see outputs like "LuaJIT 2.0.2", then you're using LuaJIT; otherwise, if you see "Not LuaJIT!", then you're using the standard Lua 5.1 interpreter.Another quicker way is to check the Lua DSO file linked with your nginx executable if dynamic linking is used (which is usually the case):ldd /path/to/your/nginx/sbin/nginx|grep -i luaIf you see something likelibluajit-5.1.so.2 => /usr/local/openresty-debug/luajit/lib/libluajit-5.1.so.2 (0x00007fb3d38f6000)Then you're using LuaJIT.
I installedhttp-lua-modulewith nginx, made a script that works perfectly fine, but now I want to be sure thatnginxusesLuaJitinstead ofLua(because my research shows that LuaJit is faster).I added to the.bushrcthose lines of code :export LD_LIBRARY_PATH=/usr/local/luajit/lib:$LD_LIBRARY_PATH export LUAJIT_LIB=/usr/local/luajit/lib export LUAJIT_INC=/usr/local/luajit/include/luajit-2.0I also recompiled nginx and now I just want to be sure that it uses LuaJit.
How to check if nginx uses LuaJit and not Lua?
$http_x_uuid is header sent by client. Response header send by upstream is $upstream_http_x_uuidhttp://wiki.nginx.org/HttpUpstreamModule#.24upstream_http_.24HEADER
We are using nginx as a reverse proxy to control and log access to a Clojure (Java) web service application.We are able to generate anaccess_logand capture incoming headers using nginx just fine. Our Clojure app logs activity via log4j. Trouble is, is that we can't match an entry in theaccess_logto an entry generated by the app.The app responds to access by sending response headers as well as a body. We can freely change these response headers. My initial thought was to generate a UUID that corresponds to each and every web service request and send that back to the user within the reply headerX-Uuid. My thought was that I could capture this response by creating a customlog_format:log_format lt-custom '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" $request_time $http_x_uuid';It's looking like nginx can capture headers in incoming requests but not outgoing replies (I verified this by replacing$http_x_uuidwith$http_content_type).So! Is there a way I can tie myaccess_logenties and my log4j entries by capturing outgoing reply headers using nginx? Is there a better way? I'd rather not have to rely on users generating their own UUIDs.Thanks so much!
nginx: Is it possible to capture response headers in access log when using nginx as a reverse proxy?
I don't know django, but I am going to assume that this issue is similar to an issue I saw trying to get the MySQL service to start on one of my servers today (see here:https://stackoverflow.com/a/55141733/708323)Basically, the "start-limit-hit" message is a red herring - service start tries to start which ever service name you provide multiple times, and if after the fifth failed attempt (for me, at least) it crashes out on the sixth attempt with "start-limit-hit". You'll need to investigate the actual syslog (possibly /var/log/syslog) to see what the real errors are that are preventing the service from starting on attempts 1-5.
I was deploying a django app and it failed because for some reason the gunicorn.socket file was not created even though before adding nginx it worked perfectly fine so I searched the internet and found thisanswerwhere the guy says that the reason for this is the virtual environment but I'm sure there must be a way around it using venv right?the log I get from nginx:connect() to unix:/run/gunicorn.sock failed (11 1: Connection refused) while connecting to upstream,error from gunicorn:gunicorn.socket: Failed with result 'service-start-limit-hit'.I'm 100% sure the problem is with gunicorn not with the setup of nginx becuase I did check for the gunicorn file and it did not exist.
gunicorn.socket: Failed with result 'service-start-limit-hit'
We manage it via separate Git repository exclusive only for nginx configuration. Yes, it includes everything inside/etc/nginx/directory.But it's not synced directly on server, instead a bash script is used to pull changes, update configuration, and reload nginx configuration.Script example:# Pull changes git pull # Sync changes excluding .git directory rsync -qauh ./* "/etc/nginx" --exclude=".git" # Set proper permissions chmod -R 644 /etc/nginx find /etc/nginx -type d -exec chmod 700 {} \; # If you store SSL certs under `/etc/nginx/ssl` # Set proper permission for SSL certs chmod -R 600 /etc/nginx/ssl chmod -R 400 /etc/nginx/ssl/* # Reload nginx config # but only if configtest is passed nginx -t && service nginx reload
currently a project my team inherited has a complete mess on the nginx configuration across 10+ environments, we would like to implement a versioning strategy however im not sure how people "normally" achieve this. you make the whole nginx conf folder a git repo and ignore what you do not want to version? or have a separate folder with the config file repo and deploy the files with a script?
Nginx Configuration Versioning Strategy