How to serve front in public folder with Rails app in Production

Tram Ho

During the last time in the project I need to use the optional font on sites like 500.html, 404.html, … depending on the font option in the vendor/assets/fonts/ of the Rails app but Still cannot get custom fonts on the above pages. After investigating, it was shown that the error page specified by nginx retrieves the response file in the public directory without going through the Rails app so the font is not served. Rails will usually perform precompile of assets when deploying to production and the file name will be appended with fingerprinting eg. application-4dd5b109ee3439da54f5bdfd78a80473.css . The problem here is how to make custom fonts serve the html pages specified by nginx?

How does Nginx serve static files?

First, we need to understand briefly how nginx serves static files . Below is the structure in the Rails app that contains the error page

In nginx’s config

With the above configuration when entering the URL on the browser www.example.com/404.html response will be a static html page specified on the server as /usr/local/rails_apps/current/public/404.html . Please continue to check in the html file when using the optional font

In the browser console section, when inspecting the element, it displays the following error To fix this error will submit the next section

Config in Rails app

Create a fonts directory under public/fonts

In file 404.html still keep the font declaration

Update Nginx config file to serve the file to use

Here we need to do 2 things: check mime types and config to allow static file serving with file format.

Mime type

In order for nginx to understand the Content-type request header, I must check cat /etc/nginx/mime.types but in this problem the required file is .otf because nginx’s default config does not have to be added to expand. Add the following using vi /etc/nginx/mime.types

Static files

Perform additional config for vi /etc/nginx/sites-enabled/default

Here I add add_header Access-Control-Allow-Methods GET; to block requests other than GET because the purpose only allows get not to be updated or deleted by other methods.

Finally, I need to restart nginx so that it can receive a new configuration with cmd sudo systemctl restart nginx .

Testing

To know the error has overcome, you can check by 2 ways:

  • Visit the error page 404.html look around the red area

  • Go to the url example example.com/fonts/ABC.otf of the font placed in the public/fonts directory and then download the font successfully.

Conclude

Hopefully this article can help you solve your problem when you encounter the same error. Thank you for reading this article. 😄

References

Share the news now

Source : Viblo