index.html vs index.php

By default when you create a new page in a project, your page name is going to be index.html. However, if you happen to add a stack to your page that requires PHP, your page will automatically be renamed to index.php. This can cause issues if you have already published your project. The reason for this is that you will have both index.html and index.php files on your server. Why is this a problem? Let's back up and learn...

Why do we want to name our pages index?

It's a best practice to always name your webpages either index.html or index.php. The reason for this is that it makes our URLs looks nicer. Lets look at these URLs...

https://www.weavers.space/stacks/index.php
https://www.weavers.space/stacks/

Both of the above URLs go to the same page. But which URL looks nicer? I think that it's the bottom one, without the page name. When we name our pages index, the web server will allow us to omit the page name from the URL and everything will still work as expected. This makes for much better looking and rememberable URLs.

Why is having both html and php files on the server bad?

By default, when a web server sees both index.html and index.php on the server, it will always prefer the HTML version of the file and server that instead of the PHP version. There are ways around that though, see below.

When we change our page names from HTML to PHP, our new page content is the PHP version. However, there web server will prefer HTML and serve up our old content.

So how do we fix this?

The fix is pretty simple. Use your favorite FTP application and delete the index.html file from your server. You can also do this from the file browser in your host's cPanel. I prefer using and FTP app though. I prefer Transmit or Forklift, but there are many out there.

How do we prevent this from happening in the future?

In your project's advanced settings, you can change the default extension to PHP. I do this in every one of my projects. This means that when I add a new page, it will always be named index.php. This way when I add a stack that requires PHP, the page is already setup to work.

You may be wondering, what if I don't have any stacks on the page that require PHP? In short, it does not matter, everything will just work as you would expect. A web page can have a PHP extension and if there isn't any PHP inside of it, it will just behave exactly as if it were an HTML page.

So there are zero downsides to making this change.

How can we change our server to default to index.php?

I stated earlier that you can configure your server so that it will default to the PHP version of an index file instead of the HTML. Add this one line to your .htaccess file on your server. Easy peasy.

DirectoryIndex index.php index.html

For more information about htaccess files, check out this article.

7
2 replies