How to Serve Static Files in Apache Web Server


serve static files in apache web server

Apache is generally used to serve dynamic content such as .php, .jsp and .asp pages. The static files on a website are usually served by NGINX. However, if you want your entire website to be served by Apache only and nothing else, then you will need to serve even static files in Apache web server. Let us take a look at how to serve static files in Apache web server.

 

How to Serve Static Files in Apache Web Server

Here are the steps to serve static files in Apache web server. Let’s say you have some images in /var/www/img folder that you want to serve via Apache.

 

1. Open Apache Config File

You will typically find Apache config file at one of the following locations, depending on the type of installation:

  • /etc/apache2/httpd.conf
  • /etc/apache2/apache2.conf
  • /etc/httpd/httpd.conf
  • /etc/httpd/conf/httpd.conf

We open it in a text editor


$ sudo vim /etc/apache2/httpd.conf

 

2. Serve Static Files

Add the following Directory directive. Replace the parts in bold as per your requirements.

<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /var/www/
Alias /images "/var/www/img/"  
<Directory "/var/www/img">  
Options +Indexes  
AllowOverride None  
Order allow,deny  
Allow from all  
</Directory>
</VirtualHost>

In the above example, we create an Alias for /images URL to be served from /var/www/img file location.

 

 

3. Restart Apache web server

Restart Apache web server to apply changes


$ sudo /etc/init.d/apache2 start [Debian or Ubuntu]
# sudo apachectl restart [RHEL, CentOS or Fedora]

 

4. Test the configuration

Open a web browser and go to http://localhost/images. You will see the images listed. If you want to disable directory listing of those files, remove Options +Indexes above.

If you have stored an image file (e.g image01.jpg), you can directly go to http://localhost/images/image01.jpg to see the image.

 

That’s it! Apache will serve static files for your website. This method is very useful in WordPress websites, which mostly use only Apache web server and nothing else to run the entire website.

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!