LazNiko LazNiko - 5 months ago 19
Apache Configuration Question

Web server for Rust as if Apache to PHP

In PHP, we have Apache (or Nginx) as the HTTP server. They are also the de-facto standard set up for PHP web development.

In Rust nearly all examples on the web are to run its own HTTP server by "Cargo run" command and then go to localhost in a browser to see the result. It seems nobody would deploy it on Apache/Nginx.

Why are Rust programs not deployed in the existing HTTP servers which provide so many useful and mature features (e.g. VirtualHost, Alias, SSL, mod_rewrite etc.)?

Also, what're the benefits of using the "Cargo run" web server over Apache/Nginx?

In a production environment, do you also use "Cargo run" as the web server for Rust?

Answer Source

The common approach when writing a web application in something other than PHP is to use either Apache or NGINX as the public-facing server. You then set up a virtual host in either Apache or NGINX to function as a remote proxy which forwards all connections to your web application (Rust, Golang, Python, Node.js, etc...) which is, itself, running its own server bound to a non-80 port on localhost.

For a (rough) visual example:

+++++++++++++++++++++++ SERVER +++++++++++++++++++++++++++++++++++
+  [Web Application (bound to localhost:8080)]                   +
+                      /|\                                       +
+                       | reverse proxy connection               +
+                      \|/                                       +
+  [NGINX (bound to remote_address::80 and remote_address:443)]  +
+++++++++++++++++++++++++/|\+++++++++++/|\++++++++++++++++++++++++
                          |             |
                         \|/           \|/
                     ++++++++++++  ++++++++++++
                     +  CLIENT  +  +  CLIENT  +
                     ++++++++++++  ++++++++++++

This approach is (generally) more secure, allows you to easily use the features of a mature web server like you are saying (e.g. SSL, load balancing, etc.), and allows you to focus on writing a robust web application rather than on writing a robust web server.

Take a look at this article for documentation on how to set up NGINX as a reverse proxy. Although Apache is just as capable, NGINX tends to be the web server of choice when creating a web application and stack like this due to its speed and the fact that it is relatively lightweight.

For what it is worth, the difference between this architecture and what, for example, PHP and Apache look like together is, simply put, that PHP runs as an "extension module" to Apache rather than as an "external component". Actually, when you use PHP with NGINX, you will have to set it up in a very similar way as described in this post.