Nginx Config for CodeIgniter in a Subdirectory
Configure Nginx to serve a CodeIgniter application installed in a subdirectory (e.g. /site) under the web root, with HTTPS and proper PHP routing.
Prerequisites
- Nginx installed with PHP-FPM
- SSL certificate in place
- CodeIgniter installed under
/home/user/public_html/site/
Nginx Server Block
Edit your Nginx virtual host configuration:
server {
listen 443 ssl;
server_name example.com www.example.com;
root /home/user/public_html/;
index index.php index.html index.htm;
ssl_certificate /etc/pki/tls/certs/example.com.bundle;
ssl_certificate_key /etc/pki/tls/private/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
# Subdirectory routing for CodeIgniter
location /site/ {
try_files $uri $uri/ /site/index.php?$args;
add_header Strict-Transport-Security "max-age=31536000";
add_header X-Content-Type-Options nosniff;
}
# Cache static assets
location ~* \.(jpeg|jpg|png|gif|bmp|ico|svg|css|js)$ {
expires max;
}
# PHP-FPM handler
location ~ [^/]\.php(/|$) {
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}Key Points
- The
try_filesdirective routes all non-file requests to CodeIgniter's front controller. - Set
$config['base_url']tohttps://example.com/site/inapplication/config/config.php. - Set
$config['index_page'] = '';to remove index.php from URLs.
Verify
nginx -t && systemctl reload nginx