Stop Safari window closing when only pinned tabs are left
If you watch the File menu, you can see ⌘W changes depending on the number of open tabs. If there are multiple, it's "Close Tab", if there is one (not counting the pinned), it's "Close Window".

There is a workaround! You can overwrite ⌘W to always execute "Close Tab".

Go to System Preferences > Keyboard > Shortcuts > App Shortcuts 

Add a Shortcut for the application "Safari", menu item "Close Tab", shortcut ⌘w.

If you're not using English in Safari, lookup the exact name of the menu item for closing a tab. In the Dutch version of Safari, the menu item is called "Sluit tabblad".