Fix 403 Forbidden on a Web Folder with SELinux Labels on Rocky 9
Permissions look right but a new folder returns 403? Check the file label with ls -Z, then make it permanent with semanage fcontext and restorecon.
A web server serving a folder outside the default /var/www, such as /var/test_www, returns 403 Forbidden. If chmod, ownership and the server config are all correct, check the SELinux file label. A 502 from a proxy is a boolean problem instead; see the Nginx proxy SELinux post.
[1] Confirm SELinux is in Enforcing mode.
# getenforce[2] Compare the labels of the new and default folders with ls -Z. The third field of the label is the type.
# ls -Zd /var/www/html /var/test_www/html[3] Look for the denial (AVC). If nothing shows up, also try journalctl -t setroubleshoot and dmesg | grep -i -e type=1300 -e type=1400, in that order.
# ausearch -m AVC,USER_AVC,SELINUX_ERR,USER_SELINUX_ERR -ts recent[4] Compare against the label policy expects. matchpathcon prints the label a path should have. Output from the official docs:
# matchpathcon /var/www/html /var/test_www/html/var/www/html system_u:object_r:httpd_sys_content_t:s0/var/test_www/html system_u:object_r:var_t:s0[5] Register the new folder so it follows the same labeling rule as the default one. This only stores the rule.
# semanage fcontext -a -e /var/www /var/test_www[6] Apply the rule to the real files. One line is printed per changed file.
# restorecon -Rv /var/test_wwwRelabeled /var/test_www/html from unconfined_u:object_r:var_t:s0 to unconfined_u:object_r:httpd_sys_content_t:s0Relabeled /var/test_www/html/index.html from unconfined_u:object_r:var_t:s0 to unconfined_u:object_r:httpd_sys_content_t:s0[7] Check the registered rule, then repeat the request.
# semanage fcontext -l | grep test_wwwWhy not chcon
chcon -t httpd_sys_content_t /var/test_www/html also clears the 403 at that moment. But the RHEL docs state that changes made with chcon are not persistent across file-system relabels. restorecon resets files to the label registered in policy, so without a semanage fcontext rule the folder returns to var_t and the same 403 comes back.
| Command | What it does | After a relabel |
|---|---|---|
chcon | Changes the file's label only | Not kept |
semanage fcontext + restorecon | Registers a rule, then applies it | Kept |