Programming

Laravel에 대한 파일 권한을 설정하는 방법은 무엇입니까?

procodes 2020. 5. 21. 21:44
반응형

Laravel에 대한 파일 권한을 설정하는 방법은 무엇입니까?


소유자가로 설정된 Apache Web Server를 사용하고 _www:_www있습니다. 새 Laravel 5 프로젝트를 만들 때와 같이 파일 권한에 대한 모범 사례가 무엇인지 절대 알 수 없습니다.

Laravel 5는 /storage쓰기 가능한 폴더가 필요 합니다. 나는 그것이 작동하게하는 많은 다른 접근법을 발견했으며 일반적으로 777chmod를 재귀 적 으로 만드는 것으로 끝납니다 . 나는 그것이 최선의 아이디어는 아니라는 것을 안다.

공식 문서는 말합니다 :

Laravel은 일부 권한을 구성해야 할 수 있습니다. 폴더 내에 storage있고 vendor웹 서버에 의한 쓰기 액세스가 필요합니다.

웹 서버가 storagevendor폴더 자체 또는 현재 컨텐츠에만 액세스해야 함을 의미합니까 ?

나는 훨씬 더 나은 것이 권한 대신 소유자변경한다고 가정합니다 . Laravel의 모든 파일 권한을 재귀 적으로 _www:_www변경했으며 chmod를로 변경 한 것처럼 사이트가 올바르게 작동했습니다 777. 문제는 이제 파일을 저장할 때마다 텍스트 편집기에서 비밀번호를 묻는 메시지가 표시되며 파일 복사와 같이 Finder에서 아무것도 변경하려고 할 때도 마찬가지입니다.

이러한 문제를 해결하는 올바른 방법은 무엇입니까?

  1. 변화 chmod
  2. 파일 소유자를 웹 서버의 소유자와 일치하도록 변경하고 텍스트 편집기 (및 Finder?)를 설정하여 비밀번호 요청을 건너 뛰거나 사용하도록 설정하십시오. sudo
  3. 웹 서버의 소유자를 운영 체제 사용자와 일치하도록 변경하십시오 (결과는 모르겠습니다)
  4. 다른 것

이 토론을 보는 모든 사람에게 명백한 설명을하기 위해 .... 폴더에 777 권한을 부여하면 누구나 해당 디렉토리의 모든 파일을 읽고 쓰고 실행할 수 있습니다 .... 이것이 의미하는 바 모든 파일, 바이러스 또는 기타 파일을 업로드하고 해당 파일을 실행할 수있는 모든 사용자 (전 세계의 모든 해커 또는 악의적 인 사용자) 권한

폴더 권한을 777로 설정 한 경우 해당 디렉토리를 찾을 수있는 사람에게 서버를 열었습니다. 충분히 클리어 ??? :)

기본적으로 소유권과 권한을 설정하는 두 가지 방법이 있습니다. 자신에게 소유권을 부여하거나 웹 서버를 모든 파일의 소유자로 만듭니다.

웹 서버 소유자 (대부분의 사람들이하는 방식과 Laravel 문서의 방식) :

www-data를 가정하면 (다른 것일 수도 있음) 웹 서버 사용자입니다.

sudo chown -R www-data : www-data / path / to / your / laravel / root / directory

그렇게하면 웹 서버가 모든 파일을 소유하고 그룹이기도하며 FTP 클라이언트가 웹 서버가 아닌 사용자로 로그인하기 때문에 FTP를 통해 파일을 업로드하거나 파일을 사용하는 데 문제가 있습니다. 웹 서버 사용자 그룹에 대한 사용자 :

sudo usermod -a -G www-data 우분투

물론 이것은 웹 서버가 www-data (홈스테드 기본값)로 실행 중이고 사용자가 우분투 (홈스테드를 사용하는 경우 비효율적)라고 가정합니다.

그런 다음 모든 디렉토리를 755로 설정하고 파일을 644로 설정하십시오. 파일 권한 설정

sudo 찾기 / path / to / your / laravel / root / directory -type f -exec chmod 644 {} \;    

SET 디렉토리 권한

sudo 찾기 / path / to / your / laravel / root / directory -type d -exec chmod 755 {} \;

소유자 인 사용자

모든 디렉토리와 파일을 소유하는 것을 선호하므로 (모든 것을 훨씬 쉽게 사용할 수 있습니다)

sudo chown -R 내 사용자 : www-data / path / to / your / laravel / root / directory

그런 다음 본인과 웹 서버 권한을 모두 부여합니다.

sudo 찾기 / path / to / your / laravel / root / directory -type f -exec chmod 664 {} \;    
sudo 찾기 / path / to / your / laravel / root / directory -type d -exec chmod 775 {} \;

그런 다음 웹 서버에 저장 및 캐시를 읽고 쓸 수있는 권한을 부여하십시오

어떤 방법으로 설정하든 저장, 캐시 및 웹 서버가 업로드 또는 쓰기 해야하는 다른 디렉토리 (상황에 따라 다름)에 대해 웹 서버에 대한 읽기 및 쓰기 권한을 부여해야하므로 위의 bashy에서 명령을 실행하십시오.

sudo chgrp -R www-data 스토리지 부트 스트랩 / 캐시
sudo chmod -R ug + rwx 스토리지 부트 스트랩 / 캐시

이제 안전하고 웹 사이트가 작동하며 파일을 매우 쉽게 사용할 수 있습니다.


보안상의 이유로 storagevendor폴더에 대한 권한 은에 유지되어야합니다 775.

그러나 컴퓨터와 서버 모두 Apache가이 폴더에 쓸 수 있어야합니다. 예 :와 같은 명령을 실행할 때 php artisan컴퓨터는의 로그 파일에 작성해야합니다 storage.

폴더의 소유권을 Apache에 제공하기 만하면됩니다.

sudo chown -R www-data:www-data /path/to/your/project/vendor
sudo chown -R www-data:www-data /path/to/your/project/storage

그런 다음 usernameApache 서버가 속한 그룹에 컴퓨터를 참조해야합니다 . 이렇게 :

sudo usermod -a -G www-data userName

참고 : 대부분의 자주 groupName입니다 www-data하지만 귀하의 경우,로 교체_www


우리는 Laravel 응용 프로그램에 대한 권한을 설정할 때 많은 경우에 부딪 쳤습니다. deployLaravel 응용 프로그램 폴더를 소유하고 CLI에서 Laravel 명령을 실행하기위한 별도의 사용자 계정 ( )을 만들고 에서 웹 서버를 실행합니다 www-data. 이 문제의 원인 중 하나는 로그 파일 을 누가 먼저 로그 파일에 썼는지에 따라 www-data또는 deploy의해 로그 파일을 소유 할 수 있기 때문에 나중에 다른 사용자가 로그 파일에 쓰지 못하게하는 것입니다.

제정신의 안전한 솔루션은 Linux ACL을 사용하는 것입니다. 이 솔루션의 목표는 다음과 같습니다.

  1. 응용 프로그램을 소유 / 배포하는 사용자가 Laravel 응용 프로그램 코드에 대한 읽기 및 쓰기 액세스 권한을 갖도록하기 위해 (우리는라는 사용자를 사용합니다 deploy).
  2. www-data사용자가 Laravel 응용 프로그램 코드에 대한 읽기 권한 을 허용 하지만 쓰기 권한은 허용하지 않습니다.
  3. 다른 사용자가 Laravel 응용 프로그램 코드 / 데이터에 전혀 액세스하지 못하도록합니다.
  4. 허용하려면 모두 www-data사용자와 응용 프로그램 사용자 ( deploy사용자가 파일 소유 (둘 정도되는 관계없이 저장 폴더) 쓰기 액세스, deploywww-data예를 들어 같은 로그 파일에 기록 할 수 있습니다).

우리는 이것을 다음과 같이 달성합니다 :

  1. application/폴더 내의 모든 파일 은 기본 umask를 사용하여 만들어 지므로 권한이 0022있는 폴더 drwxr-xr-x와 파일이 있는 폴더가 생성됩니다 -rw-r--r--.
  2. sudo chown -R deploy:deploy application/(또는 단순히 응용 프로그램을 deploy사용자 로 배포 하면됩니다.)
  3. chgrp www-data application/www-data그룹 에게 애플리케이션에 대한 액세스 권한 을 부여합니다 .
  4. chmod 750 application/허용하는 deploy사용자가 읽기 / 쓰기는 www-data사용자가 읽기 전용 및 기타 사용자에게 모든 권한을 제거 할 수 있습니다.
  5. setfacl -Rdm u:www-data:rwx,u:deploy:rwx application/storage/storage/폴더 및 모든 하위 폴더 에 대한 기본 권한을 설정합니다 . 저장 폴더에서 만든 모든 새 폴더 / 파일 (이 권한 상속 rwx모두 www-datadeploy).
  6. setfacl -Rm u:www-data:rwX,u:deploy:rwX application/storage/ 기존 파일 / 폴더에 대해 위 권한을 설정합니다.

디렉토리를 소유 한 그룹 내의 모든 사용자에 대해 읽기 / 쓰기 / 실행이 가능하도록 프로젝트 폴더의 권한을 변경하십시오 (이 경우에는 _www).

chmod -R 775 /path/to/your/project

그런 다음 OS X 사용자 이름을 _www그룹에 추가하여 디렉토리에 액세스 할 수 있도록하십시오.

sudo dseditgroup -o edit -a yourusername -t user _www

이미 게시 된대로

폴더의 소유권을 Apache에 제공하기 만하면됩니다.

그러나 chown 명령 -R추가했습니다 . sudo chown -R www-data:www-data /path/to/your/project/vendor sudo chown -R www-data:www-data /path/to/your/project/storage


대부분의 폴더는 일반 "755"및 파일 "644"여야합니다.

Laravel requires some folders to be writable for the web server user. You can use this command on unix based OSs.

sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache

The Laravel 5.4 docs say:

After installing Laravel, you may need to configure some permissions. Directories within the storage and the bootstrap/cache directories should be writable by your web server or Laravel will not run. If you are using the Homestead virtual machine, these permissions should already be set.

There are a lot of answers on this page that mention using 777 permissions. Don't do that. You'd be exposing yourself to hackers.

Instead, follow the suggestions by others about how to set permissions of 755 (or more restrictive). You may need to figure out which user your app is running as by running whoami in the terminal and then change ownership of certain directories using chown -R.

If you do not have permission to use sudo as so many other answers require...

Your server is probably a shared host such as Cloudways.

(In my case, I had cloned my Laravel application into a second Cloudways server of mine, and it wasn't completely working because the permissions of the storage and bootstrap/cache directories were messed up.)

I needed to use:

Cloudways Platform > Server > Application Settings > Reset Permission

Then I could run php artisan cache:clear in the terminal.


The solution posted by bgles is spot on for me in terms of correctly setting permissions initially (I use the second method), but it still has potential issues for Laravel.

By default, Apache will create files with 644 permissions. So that's pretty much anything in storage/. So, if you delete the contents of storage/framework/views, then access a page through Apache you will find the cached view has been created like:

-rw-r--r-- 1 www-data www-data 1005 Dec  6 09:40 969370d7664df9c5206b90cd7c2c79c2

If you run "artisan serve" and access a different page, you will get different permissions because CLI PHP behaves differently from Apache:

-rw-rw-r-- 1 user     www-data 16191 Dec  6 09:48 2a1683fac0674d6f8b0b54cbc8579f8e

In itself this is no big deal as you will not be doing any of this in production. But if Apache creates a file that subsequently needs to be written by the user, it will fail. And this can apply to cache files, cached views and logs when deploying using a logged-in user and artisan. A facile example being "artisan cache:clear" which will fail to delete any cache files that are www-data:www-data 644.

This can be partially mitigated by running artisan commands as www-data, so you'll be doing/scripting everything like:

sudo -u www-data php artisan cache:clear

Or you'll avoid the tediousness of this and add this to your .bash_aliases:

alias art='sudo -u www-data php artisan'

This is good enough and is not affecting security in any way. But on development machines, running testing and sanitation scripts makes this unwieldy, unless you want to set up aliases to use 'sudo -u www-data' to run phpunit and everything else you check your builds with that might cause files to be created.

The solution is to follow the second part of bgles advice, and add the following to /etc/apache2/envvars, and restart (not reload) Apache:

umask 002

This will force Apache to create files as 664 by default. In itself, this can present a security risk. However, on the Laravel environments mostly being discussed here (Homestead, Vagrant, Ubuntu) the web server runs as user www-data under group www-data. So if you do not arbitrarily allow users to join www-data group, there should be no additional risk. If someone manages to break out of the webserver, they have www-data access level anyway so nothing is lost (though that's not the best attitude to have relating to security admittedly). So on production it's relatively safe, and on a single-user development machine, it's just not an issue.

Ultimately as your user is in www-data group, and all directories containing these files are g+s (the file is always created under the group of the parent directory), anything created by the user or by www-data will be r/w for the other.

And that's the aim here.

edit

On investigating the above approach to setting permissions further, it still looks good enough, but a few tweaks can help:

By default, directories are 775 and files are 664 and all files have the owner and group of the user who just installed the framework. So assume we start from that point.

cd /var/www/projectroot
sudo chmod 750 ./
sudo chgrp www-data ./

First thing we do is block access to everyone else, and make the group to be www-data. Only the owner and members of www-data can access the directory.

sudo chmod 2775 bootstrap/cache
sudo chgrp -R www-data bootstrap/cache

To allow the webserver to create services.json and compiled.php, as suggested by the official Laravel installation guide. Setting the group sticky bit means these will be owned by the creator with a group of www-data.

find storage -type d -exec sudo chmod 2775 {} \;
find storage -type f -exec sudo chmod 664 {} \;
sudo chgrp -R www-data storage

We do the same thing with the storage folder to allow creation of cache, log, session and view files. We use find to explicitly set the directory permissions differently for directories and files. We didn't need to do this in bootstrap/cache as there aren't (normally) any sub-directories in there.

You may need to reapply any executable flags, and delete vendor/* and reinstall composer dependencies to recreate links for phpunit et al, eg:

chmod +x .git/hooks/*
rm vendor/*
composer install -o

That's it. Except for the umask for Apache explained above, this is all that's required without making the whole projectroot writeable by www-data, which is what happens with other solutions. So it's marginally safer this way in that an intruder running as www-data has more limited write access.

end edit

Changes for Systemd

This applies to the use of php-fpm, but maybe others too.

The standard systemd service needs to be overridden, the umask set in the override.conf file, and the service restarted:

sudo systemctl edit php7.0-fpm.service
Use:
    [Service]
    UMask=0002
Then:
sudo systemctl daemon-reload
sudo systemctl restart php7.0-fpm.service

I have installed laravel on EC2 instance and have spent 3 days to fix the permission error and at last fixed it. So I want to share this experience with other one.

  1. user problem When I logged in ec2 instance, my username is ec2-user and usergroup is ec2-user. And the website works under of httpd user: apache: apache so we should set the permission for apache.

  2. folder and file permission A. folder structure first, you should make sure that you have such folder structure like this under storage

    storage

    • framework
      • cache
      • sessions
      • views
    • logs The folder structure can be different according to the laravel version you use. my laravel version is 5.2 and you could find the appropriate structure according to your version.

B. permission At first, I see the instructions to set 777 under storage to remove file_put_contents: failed to open stream error. So i setup permission 777 to storage chmod -R 777 storage But the error was not fixed. here, you should consider one: who writes files to storage/ sessions and views. That is not ec2-user, but apache. Yes, right. "apache" user writes file (session file, compiled view file) to the session and view folder. So you should give apache to write permission to these folder. By default: SELinux say the /var/www folder should be read-only by the apache deamon.

So for this, we can set the selinux as 0: setenforce 0

This can solve problem temporally, but this makes the mysql not working. so this is not so good solution.

You can set a read-write context to the storage folder with: (remember to setenforce 1 to test it out)

chcon -Rt httpd_sys_content_rw_t storage/

Then your problem will be fixed.

  1. and don't forget this composer update php artisan cache:clear

    These commands will be useful after or before.

    I hope you save your time. Good luck. Hacken


Add to composer.json

"scripts": {
    "post-install-cmd": [
      "chgrp -R www-data storage bootstrap/cache",
      "chmod -R ug+rwx storage bootstrap/cache"
    ]
}

After composer install


I decided to write my own script to ease some of the pain of setting up projects.

Run the following inside your project root:

wget -qO- https://raw.githubusercontent.com/defaye/bootstrap-laravel/master/bootstrap.sh | sh

Wait for the bootstrapping to complete and you're good to go.

Review the script before use.


I had the following configuration:

  • NGINX (running user: nginx)
  • PHP-FPM

And applied permissions correctly as @bgies suggested in the accepted answer. The problem in my case was the php-fpm's configured running user and group which was originally apache.

If you're using NGINX with php-fpm, you should open php-fpm's config file:

nano /etc/php-fpm.d/www.config

And replace user and group options' value with one NGINX is configured to work with; in my case, both were nginx:

... ; Unix user/group of processes ; Note: The user is mandatory. If the group is not set, the default user's group ; will be used. ; RPM: apache Choosed to be able to access some dir as httpd user = nginx ; RPM: Keep a group allowed to write in log dir. group = nginx ...

Save it and restart nginx and php-fpm services.


I found an even better solution to this. Its caused because php is running as another user by default.

so to fix this do

sudo nano /etc/php/7.0/fpm/pool.d/www.conf

then edit the user = "put user that owns the directories" group = "put user that owns the directories"

then:

sudo systemctl reload php7.0-fpm

참고URL : https://stackoverflow.com/questions/30639174/how-to-set-up-file-permissions-for-laravel

반응형