SIP preventing deletion of /opt/local

Solution 1:

The directory is SIP-protected because it is the home directory for a macports user, presumably created as part of the MacPorts installation process.

The best solution is to first remove that user account, following the instructions in this accepted answer to another AppleSE question. You may also wish to remove the corresponding macports group that also exists.

Specifically, the following commands will remove the user and group:

sudo /usr/bin/dscl . -delete "/Users/macports"
sudo /usr/bin/dscl . -delete "/Groups/macports"

The MacPorts website uninstall page mentions deleting the user and group but does not note that it is necessary due to SIP-protection to do this before deleting the folders. I think they also have an error in the syntax of their dscl command.

Once you have done that, you should be able to sudo rm -rf /opt/local successfully.

Significant credit for this answer is due to @GordonDavisson for providing 90% of the solution in comments, some months ago.