误删tmp目录nginx.pid及tmp文件内容,如何重建并解决Nginx报错?
Hey there, let's work through these two Nginx issues step by step—they’re both straightforward to fix!
First up, the error about failing to open /var/log/nginx/error.log and access.log likely happened because those files (or maybe the entire /var/log/nginx directory) were accidentally removed during your cleanup. Here’s how to fix it:
- First, make sure the
/var/log/nginxdirectory exists. If it was deleted, create it with:sudo mkdir -p /var/log/nginx - Next, create the missing log files:
sudo touch /var/log/nginx/error.log /var/log/nginx/access.log - Critical step: Set the correct ownership so the Nginx process can read/write these files. Nginx typically runs as the
nginxorwww-datauser—check which one withps aux | grep nginx, then run:# Replace nginx:nginx with www-data:www-data if your Nginx uses that user sudo chown -R nginx:nginx /var/log/nginx - Now test your configuration again—this should resolve the log-related errors:
sudo nginx -t -c /etc/nginx/nginx.conf
/tmp/nginx.pid File The nginx.pid file doesn’t need to be manually written—Nginx creates it automatically when it starts. Here’s what to do:
- First, confirm that the
/tmpdirectory exists and has the right permissions (since you deleted its contents, the directory itself should still be there, but double-check):
The permissions should showls -ld /tmpdrwxrwxrwt—if not, fix them with:sudo chmod 1777 /tmp - Next, check where your Nginx configuration expects the pid file to be. Run this grep command to verify:
If it showsgrep -i pid /etc/nginx/nginx.confpid /tmp/nginx.pid;, that’s the path we need. If it’s set to another location (like the default/var/run/nginx.pid), adjust the verification step below accordingly. - Finally, restart Nginx. This will trigger Nginx to generate the pid file in the configured path:
# For systemd systems (most modern distros like Ubuntu 16.04+, CentOS 7+) sudo systemctl restart nginx # For older systems using init.d sudo service nginx restart - Verify it worked by checking if the pid file exists:
ls /tmp/nginx.pid
A quick heads-up: Avoid deleting all files in /tmp blindly—many services rely on temporary files, sockets, and pid files stored there. If you need to clean up /tmp, use tools like sudo tmpwatch that safely remove old unused files instead of wiping everything.
内容的提问来源于stack exchange,提问作者enigmq

