How to Remove 'public' from Your CodeIgniter 4 URL
How to Remove 'public' from Your CodeIgniter 4 URL

Taming Your URLs: How to Remove ‘public’ from Your CodeIgniter 4 Application12 min read

  Reading time 16 minutes

If you’re just starting with CodeIgniter 4, you might have noticed that your web application’s URL includes the word “/public”. For instance, instead of http://yourwebsite.com/dashboard, you see http://yourwebsite.com/public/dashboard. While this structure is the default and offers a security advantage by isolating your application’s core files, it can look less clean and isn’t always the desired URL presentation for a production website.

The good news? You can absolutely remove that “public” segment from your URLs. This guide will walk you through the process step-by-step, explaining the most recommended method and a common alternative, so you can have clean, user-friendly URLs for your CodeIgniter 4 project.  

Why is ‘public’ There in the First Place?

Before we dive into removing it, let’s understand why CodeIgniter 4 uses the public directory by default. This structure is a security best practice. The public folder is the only directory that should be directly accessible by the web server. It contains your index.php file (the main entry point for your application), your assets (CSS, JavaScript, images), and typically your .htaccess file (for Apache).

All your sensitive application code, configurations, system files, and views are kept outside the public directory. This prevents users from directly accessing potentially vulnerable files by typing their paths in the browser. When you access your application through the public directory, the index.php file bootstraps the CodeIgniter framework, handles the request, and serves the appropriate response, all while keeping your core application logic protected.

So, while we’re going to remove “public” from the URL visible to the user, we need to ensure the web server still correctly points to this directory as the entry point. Simply moving files around without proper server configuration can expose your application to security risks.

The most secure and recommended way to remove “public” from your URL is to configure your web server (like Apache or Nginx) to point its document root directly to your CodeIgniter 4 project’s public directory. This way, when someone visits http://yourwebsite.com, the web server automatically looks inside the public folder without the user having to include it in the URL.

This method keeps all your application files outside the web-accessible directory, maintaining the security benefits of CodeIgniter’s default structure.

Let’s look at how to do this for the two most common web servers: Apache and Nginx.

For Apache Web Server

If you’re using Apache for CodeIgniter 4, you’ll typically configure your virtual host to point to the public directory. The virtual host configuration file location can vary depending on your operating system and Apache installation, but it’s often found in a directory like /etc/apache2/sites-available/ or /etc/httpd/conf/sites-available/.

Here’s an example of what your Apache virtual host configuration might look like before and after changing the document root:

Before (Default – Access via /public)

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/your-codeigniter-project # Points to the project root
    ServerName yourwebsite.com

    <Directory /var/www/html/your-codeigniter-project>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

After (Recommended – Access directly)

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/your-codeigniter-project/public # Points to the public directory
    ServerName yourwebsite.com

    <Directory /var/www/html/your-codeigniter-project/public>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Key Change:

Notice the DocumentRoot line. We’ve changed it from pointing to the project’s root directory (/var/www/html/your-codeigniter-project) to pointing specifically to the public subdirectory (/var/www/html/your-codeigniter-project/public).

Also, ensure the <Directory> block points to the public directory as well and has AllowOverride All enabled so Apache can read the .htaccess file located inside the public folder.

Steps to Apply the Change:

  1. Locate your virtual host file: This is usually in /etc/apache2/sites-available/ on Debian/Ubuntu or /etc/httpd/conf/sites-available/ on CentOS/RHEL. You might be editing a file like 000-default.conf or a file named after your website.
  2. Edit the DocumentRoot directive: Change the path to include /public at the end.
  3. Update the <Directory> block: Make sure the path in the <Directory> tag also points to the public directory.
  4. Save the file.
  5. Enable the site (if it’s a new config): On Debian/Ubuntu, you might need to run sudo a2ensite your-config-file.conf.
  6. Test your Apache configuration: Run sudo apache2ctl configtest (Debian/Ubuntu) or sudo httpd -t (CentOS/RHEL). Fix any errors.  
  7. Reload or restart Apache: Run sudo systemctl reload apache2 or sudo systemctl restart apache2 (Debian/Ubuntu), or sudo systemctl reload httpd or sudo systemctl restart httpd (CentOS/RHEL).  

After these steps, you should be able to access your CodeIgniter 4 application directly using http://yourwebsite.com without needing /public in the URL.

For Nginx Web Server – CodeIgniter 4

If you’re using Nginx, you’ll configure your server block to point its root to the public directory. Nginx configuration files are typically located in /etc/nginx/sites-available/.

Here’s an example of a basic Nginx server block configured to serve a CodeIgniter 4 application:

server {
    listen 80;
    server_name yourwebsite.com;
    root /var/www/html/your-codeigniter-project/public; # Points to the public directory
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/phpX.X-fpm.sock; # Change X.X to your PHP version
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }
}

Key Changes (CodeIgniter 4):

  1. root directive: The root directive is set to the full path of your project’s public directory.
  2. location / block: The try_files directive is crucial here. It tells Nginx to first look for a file or directory that matches the requested URI. If it doesn’t find one, it internally rewrites the request to index.php, passing along any query arguments. This ensures that all requests are routed through CodeIgniter’s front controller (index.php) unless a static file or directory exists.
  3. location ~ \.php$ block: This block handles the execution of PHP files, specifically index.php. Ensure the fastcgi_pass setting points to your PHP-FPM socket or address.

Steps to Apply the Change: (CodeIgniter 4)

  1. Locate your server block file: This is usually in /etc/nginx/sites-available/. You might be editing a file named after your website.
  2. Edit the root directive: Change the path to include /public at the end.
  3. Ensure the location / and location ~ \.php$ blocks are correctly configured: Use the try_files directive as shown above to route requests through index.php.
  4. Save the file.
  5. Create a symbolic link (if needed): Nginx uses sites-available for configuration files and sites-enabled for active sites. If your configuration is in sites-available, create a symbolic link to it in sites-enabled: sudo ln -s /etc/nginx/sites-available/your-config-file /etc/nginx/sites-enabled/.
  6. Test your Nginx configuration: Run sudo nginx -t. Fix any errors.
  7. Reload or restart Nginx: Run sudo systemctl reload nginx or sudo systemctl restart nginx.

With these Nginx configurations, your CodeIgniter 4 application should be accessible without the /public segment in the URL.

Another method, often used on shared hosting environments where you cannot change the web server’s document root, involves moving the index.php file and the .htaccess file (for Apache) from the public folder to the project’s root directory. You then modify the index.php file to correctly point to the application files.

Why this is less recommended:

  • Security: Moving index.php and .htaccess to the root directory means your project’s root is now web-accessible. While CodeIgniter’s structure still provides some protection, it slightly increases the attack surface compared to having the web server point directly to the public folder. Sensitive files like your .env file are now in the web-accessible root directory, although they should still be protected by web server configuration to prevent direct access.
  • Clarity: It slightly deviates from the standard CodeIgniter 4 project structure, which can be confusing for other developers working on the project.

If you understand the potential drawbacks and are on a hosting environment where configuring the document root is not possible, here are the steps for Apache (CodeIgniter 4):

Steps for Apache (Moving Files):

  • Copy index.php and .htaccess: Copy the index.php and .htaccess files from your public directory to the root directory of your CodeIgniter 4 project.
cp public/index.php .
cp public/.htaccess .
  • Edit the root index.php file: Open the index.php file you just copied to the root directory. Find the line that defines $pathsConfig. It will likely look like this:
$pathsConfig = FCPATH . '../app/Config/Paths.php';
  • This line uses ../ to go up one directory to find the app folder because the original index.php was inside public. Since you’ve moved index.php to the root, you need to remove the ../:
$pathsConfig = FCPATH . 'app/Config/Paths.php';
  • Ensure the root .htaccess is configured: The .htaccess file you copied from the public folder usually contains the necessary rewrite rules to remove index.php from the URL and route requests correctly. Ensure it looks something like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

This tells Apache to rewrite requests that don’t map to a physical file or directory to index.php, passing the requested URI as an argument.  

After these steps, you should be able to access your application without /public in the URL on an Apache server.

Note for Nginx: Moving files and relying on a .htaccess equivalent in the root is not the standard or recommended approach for Nginx, as Nginx does not process .htaccess files. You would typically configure rewrite rules directly in your Nginx server block, similar to the recommended method, but potentially with different pathing if your document root cannot be changed from the project root. However, configuring the document root to the public folder remains the superior method for Nginx as well.

Updating Your CodeIgniter Configuration (CodeIgniter 4 : App.php)

Regardless of which method you use to remove “public” from the URL, it’s a good practice to update your application’s base URL in the CodeIgniter configuration. This helps CodeIgniter’s URL helper functions generate correct URLs.

  • Open the App.php configuration file: This file is located at app/Config/App.php.
  • Find the $baseURL property:
public $baseURL = 'http://localhost:8080/';

(The exact value might differ based on your initial setup).

Update the $baseURL: Change this value to your website’s base URL without the /public segment.

public $baseURL = 'http://yourwebsite.com/';

Or, if you’re working locally, set it to your local development URL:

public $baseURL = 'http://localhost/your-project-folder-name/';

Make sure it ends with a trailing slash /.

  • Find the $indexPage property:
public $indexPage = 'index.php';
  • Remove ‘index.php’ from $indexPage: Since we’ve configured the web server or used rewrite rules to handle index.php implicitly, you can remove it from this setting:
public $indexPage = '';
  • This ensures that CodeIgniter’s URL generation functions (like site_url()) don’t include “index.php” in the generated URLs.
  • Save the App.php file.

By updating your $baseURL and $indexPage in App.php, you ensure that CodeIgniter is aware of your desired URL structure, which helps prevent issues with generated links and redirects within your application.

Potential Issues and Troubleshooting

  • 404 Errors: If you’re getting 404 errors after making the changes, double-check your web server configuration (virtual host or server block). Ensure the DocumentRoot is pointing to the correct public directory and that rewrite rules are correctly configured and enabled (for Apache, check if mod_rewrite is enabled).
  • Assets Not Loading: If your CSS, JavaScript, or images aren’t loading, check the paths to these assets in your HTML. Use CodeIgniter’s base_url() helper function to generate the correct paths to your assets, as this will correctly point to the public directory (which is now your web root). For example: HTML
<link href="<?= base_url('css/style.css') ?>" rel="stylesheet">
  • Internal Server Errors (500): This could be caused by errors in your .htaccess file (for Apache) or Nginx configuration. Check your web server’s error logs for more details. Also, ensure file permissions are correct for your project files and directories.
  • Changes Not Taking Effect: After modifying web server configuration files, always remember to test the configuration and reload or restart the web server service.

Summary of Methods

MethodDescriptionProsConsRecommended For
Configure Web Server Document RootPoint the web server directly to the public directory.Most secure, clean URLs, follows best practices.Requires access to web server configuration.VPS, Dedicated Servers, Local Development
Move Files & Use Rewrite RulesMove index.php and .htaccess to the root and adjust paths/rules.Works on shared hosting where document root changes aren’t allowed.Less secure, deviates from standard structure, .env in web root.Shared Hosting (if no document root access)

For most development and production environments (VPS, dedicated servers, or your local machine), configuring the web server’s document root is the preferred and most secure approach.

Conclusion

Removing “/public” from your CodeIgniter 4 URLs is a straightforward process that significantly improves the appearance and usability of your web application’s addresses. By correctly configuring your web server’s document root or, as an alternative, carefully moving files and setting up rewrite rules, you can achieve clean URLs while still leveraging CodeIgniter’s robust security features. Remember to update your baseURL and $indexPage in App.php for seamless URL generation within your application. Choose the method that best suits your hosting environment, prioritizing the recommended document root configuration whenever possible for enhanced security.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply