Report this

What is the reason for this report?

Nginx - How to serve rails app on subdomain and static html on domain?

Posted on May 7, 2015

Hi there!

I have successfully deployed a doplet using ubuntu + rails + nginx + unicorn. Everything is up and running.

Ideally I would like app.mydomain.com to run my ruby application and mydomain.com to serve static html content. Is that something that’s possible with nginx?

Thanks! Alex



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

@asb thanks!! very useful!!

That’s definitely possible. You’ll just need to define a new server block in your Nginx configuration, pointing to the directory holding the static files. You also need to set server_name for each block so Nginx knows how to direct the requests.

Here’s an example:

  1. upstream app_server { server 127.0.0.1:8080 fail_timeout=0; }
  2. server {
  3. listen 80;
  4. root /home/rails/public;
  5. server_name app.mydomain.com;
  6. index index.htm index.html;
  7. location / {
  8. try_files $uri/index.html $uri.html $uri @app;
  9. }
  10. location ~* ^.+\.(jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|mp3|flv|mpeg|avi)$ {
  11. try_files $uri @app;
  12. }
  13. location @app {
  14. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  15. proxy_set_header Host $http_host;
  16. proxy_redirect off;
  17. proxy_pass http://app_server;
  18. }
  19. }
  20. server {
  21. listen 80;
  22. root /var/www/html;
  23. server_name mydomain.com;
  24. index index.htm index.html;
  25. location / {
  26. try_files $uri $uri/ =404;
  27. }
  28. error_page 404 /404.html;
  29. error_page 500 502 503 504 /50x.html;
  30. location = /50x.html {
  31. root /usr/share/nginx/html;
  32. }
  33. }

For more information, check out these tutorials:

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.