Apache not serving assets - Rails 5, Puma, Apache, Windows Server 2012 R2 - ruby-on-rails

I can't get css and js to render with Apache for my Rails 5 app running Puma. I've seen similar questions asked about this issue but none have worked for me so I think it might be specific to this stack or because I'm missing something about the location match in my httpd-vhosts.conf file. Here's what I have:
<VirtualHost *:80>
ServerName clientdb
DocumentRoot "C:/Bitnami/rubystack-2.2.7-0/projects/clientdb/public/"
<Directory "C:/Bitnami/rubystack-2.2.7-0/projects/clientdb/public/" >
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
<Proxy *>
Order allow,deny
Allow from all
</Proxy>
<Proxy balancer://puma_cluster>
BalancerMember http://127.0.0.1:3003
BalancerMember http://127.0.0.1:3004
</Proxy>
ProxyPass /favicon.ico !
ProxyPass /robots.txt !
ProxyPassMatch ^/(404|422|500).html$ !
ProxyPass /assets/ !
ProxyPass / balancer://puma_cluster/
# enumerate all nodes for proxypassreverse since it adds a trailing slash :( bugid 51982
ProxyPassReverse / http://127.0.0.1:3003
ProxyPassReverse / http://127.0.0.1:3004
# ProxyPass / balancer://puma_cluster/ lbmethod=byrequests
# ProxyPass / balancer://puma_cluster/ lbmethod=bytraffic
# ProxyPass / balancer://puma_cluster/ lbmethod=bybusyness
<FilesMatch \.css\.gz$>
ForceType text/css
Header set Content-Encoding gzip
</FilesMatch>
<FilesMatch \.js\.gz$>
ForceType text/javascript
Header set Content-Encoding gzip
</FilesMatch>
<Location /assets/>
# Use of ETag is discouraged when Last-Modified is present
Header unset ETag
FileETag None
# RFC says only cache for 1 year
ExpiresActive On
ExpiresDefault "access plus 1 year"
</Location>
<LocationMatch "^/assets/.*\.(css|js)$">
RewriteEngine on
# Make sure the browser supports gzip encoding before we send it,
# and that we have a precompiled .gz version.
RewriteCond %{HTTP:Accept-Encoding} \b(x-)?gzip\b
RewriteCond %{REQUEST_FILENAME}.gz -s
RewriteRule ^(.+)$ $1.gz
</LocationMatch>
# Make sure Content-Type is set for 'real' type, not gzip,
# and Content-Encoding is there to tell browser it needs to
# unzip to get real type.
# Make sure Vary header is set; while apache docs suggest it
# ought to be set automatically by our RewriteCond that uses an HTTP
# header, does not seem to be reliably working.
<LocationMatch "^/assets/.*\.css\.gz$">
ForceType text/css
Header set Content-Encoding gzip
Header add Vary Accept-Encoding
</LocationMatch>
<LocationMatch "^/assets/.*\.js\.gz$">
ForceType application/javascript
Header set Content-Encoding gzip
Header add Vary Accept-Encoding
</LocationMatch>
And this is config/environments/production.rb. (I have tried both enabling and disabling the static file server and neither works)
Rails.application.configure do
# Settings specified here will take precedence over those in
config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
config.threadsafe!
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable serving static files from the `/public` folder by default
since
# Apache or NGINX already handles this.
# config.public_file_server.enabled =
ENV['RAILS_SERVE_STATIC_FILES'].present?
config.public_file_server.enabled = false
# config.public_file_server.enabled = true
# Compress JavaScripts and CSS.
# config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# config.assets.prefix = '/clientdb/public/assets'
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# added by KO to try fix for serving assets on apache
# config.assets.digest = true
# config.assets.debug = true
# Enable serving of images, stylesheets, and JavaScripts from an asset
server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
What am I missing here? I'm able to get bootstrap to render using the CDN but the rest is still missing and ideally I'd like to keep my asset pipeline intact. If I have to use CDN's then so be it, but I feel like this it probably just a tweak.

You need a "/" at the end of your ProxyPassReverse statements.
A similar question was asked here: https://stackoverflow.com/a/9929360/4038302

Related

Rails, Nginx, Passenger, SSL - File Uploads Not Working

I am not able to get uploads to work with Passenger-Nginx and SSL. Uploads work fine if I disable SSL.
Here is my Nginx site config:
server {
listen 80;
server_name www.mysite.in;
root /home/deploy/mysite/current/public;
passenger_enabled on;
passenger_ruby /home/deploy/.rvm/gems/ruby-2.1.4/wrappers/ruby;
passenger_user deploy;
}
server {
listen 443 ssl;
server_name www.mysite.in;
root /home/deploy/mysite/current/public;
passenger_enabled on;
passenger_ruby /home/deploy/.rvm/gems/ruby-2.1.4/wrappers/ruby;
passenger_user deploy;
ssl on;
ssl_certificate /etc/nginx/ssl/www_mysite_in.crt;
ssl_certificate_key /etc/nginx/ssl/myserver.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
#Disables all weak ciphers
ssl_ciphers 'AES256+EECDH:AES256+EDH';
# Specifies that server ciphers should be preferred over client (e.g. browser) ciphers when using SSL/TLS.
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.4.4 8.8.8.8 valid=300s;
resolver_timeout 10s;
passenger_set_cgi_param HTTP_X_FORWARDED_PROTO https;
}
Any config/environments/production.rb
Mysite::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# config.action_mailer.delivery_method = :sendmail
end
I have tried disabling the config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' and it makes no difference under SSL or non-SSL.
I was never able to get this to work. So I just deleted the VPS image, and created a new one... and it works.
PS - I was using a setup script to install all the packages, so I am at a total loss as to why it didn't work with the original VPS image.

Trouble configuring a sub-uri with Apache 2, Rails 3.2, and Phusion Passenger

I need some help getting a Rails 3.2 app working in a sub-uri of a cPanel-configured Apache site. I've followed the steps from the Passenger docs and various blog posts. The root action renders fine, but every other request gives me a 404.
I think it is something in the Apache, not Rails, config, because it's not the Rails app's 404 page, and the 404s do not leave traces in the Rails log.
Here is the vhost section from httpd.conf, generated by cPanel:
<VirtualHost myip:443>
ServerName mysite.org
ServerAlias www.mysite.org
DocumentRoot /home/myuser/public_html
ServerAdmin webmaster#mysite.org
UseCanonicalName Off
Options -ExecCGI -Includes
RemoveHandler cgi-script .cgi .pl .plx .ppl .perl
CustomLog /usr/local/apache/domlogs/mysite.org combined
CustomLog /usr/local/apache/domlogs/mysite.org-bytes_log "%{%s}t %I .\n%{%s}t %O ."
## User myuser # Needed for CPanel::ApacheConf
UserDir disabled
UserDir enabled myuser
<IfModule mod_suphp.c>
suPHP_UserGroup myuser myuser
</IfModule>
<IfModule !mod_disable_suexec.c>
<IfModule !mod_ruid2.c>
SuexecUserGroup myuser myuser
</IfModule>
</IfModule>
<IfModule mod_ruid2.c>
RUidGid myuser myuser
</IfModule>
SSLEngine on
SSLCertificateFile /etc/ssl/certs/mysite.org.crt
SSLCertificateKeyFile /etc/ssl/private/mysite.org.key
SSLCACertificateFile /etc/ssl/certs/mysite.org.cabundle
CustomLog /usr/local/apache/domlogs/mysite.org-ssl_log combined
SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown
<Directory "/home/myuser/public_html/cgi-bin">
SSLOptions +StdEnvVars
</Directory>
Include "/usr/local/apache/conf/userdata/ssl/2/myuser/mysite.org/*.conf"
</VirtualHost>
Here is the current version of the include file I put together for the sub-uri:
RewriteEngine On
RewriteOptions Inherit
RailsEnv production
<Directory /home/myuser/public_html>
Options Indexes FollowSymLinks -MultiViews
AllowOverride all
Order allow,deny
Allow from all
</Directory>
RackBaseURI /home/myrailsapp/current
<Directory /home/myuser/public_html/railsapp>
Options -MultiViews
</Directory>
/home/myuser/public_html/railsapp is a symlink to /home/myrailsapp/current/public
Here is /home/myrailsapp/current/public/.htaccess
RackBaseURI /railsapp
SetEnv GEM_HOME /usr/local/lib/ruby/gems
PassengerEnabled On
PassengerAppRoot /home/myrailsapp/current/
All files in /home/myrailsapp and /home/mysite are owned by myuser. (I'm not seeing any permissions errors.)
In my routes file:
resources :widgets
root :to => 'widgets#index'
When I navigate to https://mysite.org/railsapp it correctly displays the widgets index, including assets. When I go to https://mysite.org/railsapp/widgets or https://mysite.org/railsapp/widgets/index, I get the Apache 404, and no entry in the Rails log.
What am I missing?
It turns out .htaccess in /home/myuser/public_html was rewriting everything. Requests for /mysite/railsapp were exempted because it matched a directory name. I solved the problem by adding
RewriteEngine off
to /home/myrailsapp/current/public/.htaccess.
Adding RewriteEngine off to .htaccess does solve the problem.

Apache crashing when I add Far-Future Expires clause from Rails Guide

In an attempt to serve my precompiled assets with Apache, per this Rails Guide I try to change this:
<VirtualHost *:82>
ServerName localhost
DocumentRoot "C:/RubyStack-3.2.5-0/projects/release_checklist/public"
<Directory "C:/RubyStack-3.2.5-0/projects/release_checklist/public">
Allow from all
Options -MultiViews
</Directory>
ProxyPass / http://localhost:3001/
ProxyPassReverse / http://localhost:3001/
ProxyPreserveHost On
</VirtualHost>
To this:
<VirtualHost *:82>
ServerName localhost
DocumentRoot "C:/RubyStack-3.2.5-0/projects/release_checklist/public"
<Directory "C:/RubyStack-3.2.5-0/projects/release_checklist/public">
Allow from all
Options -MultiViews
</Directory>
ProxyPass / http://localhost:3001/
ProxyPassReverse / http://localhost:3001/
ProxyPreserveHost On
<LocationMatch "^/assets/.*$">
Header unset ETag
FileETag None
# RFC says only cache for 1 year
ExpiresActive On
ExpiresDefault "access plus 1 year"
</LocationMatch>
</VirtualHost>
in my httpd.conf file. However, the Apache server won't start when the second option has been added. What am I doing wrong?
What error does it give you? Are you sure you have mod_expires compiled into apache and that the module is loaded?
Invalid command 'ExpiresActive', perhaps misspelled or defined by a module not included in the server configuration
Yeah, that's usually the error you get if you use a directive that's mapped to a module that isn't loaded (or just a mispelled directive, which appears the same to apache). You'll need to check httpd.conf and make sure the LoadModule expires_module modules/mod_expires.so line is not commented out, of if it's missing, to add it. Depending on your apache's version, the line can be slightly different.

Request exceeded the limit of 10 internal redirects due to probable configuration error

I was trying to remove index.php from the URL of a Magento website:
_Turn on “use webserver rewrite”
_ Set permission 755 to necessary files and folders
_ make sure mode rewrite is on
_ configure htaccess file. comment, uncomment allow symlinks, change rewrite base from /magento/ to / or /var/www/hosts/www.domainname.com/ or /hosts/www.domainname.com/ or /www.domainname.com/
_reindex, flush cache
But all results in 500 server internal error.
In the log file I can see:
[Fri Apr 20 11:11:59 2012] [error] [client 88.87.40.140] client denied by server configuration: /var/www/hosts/www.nordocks.no/app/etc/local.xml
[Fri Apr 20 11:12:07 2012] [error] [client 117.5.178.168] Request exceeded the limit of 10 internal redirects due to probable configuration error.
And this is my .htaccess
############################################
## uncomment these lines for CGI mode
## make sure to specify the correct cgi php binary file name
## it might be /cgi-bin/php-cgi
# Action php5-cgi /cgi-bin/php5-cgi
# AddHandler php5-cgi .php
############################################
## GoDaddy specific options
# Options -MultiViews
## you might also need to add this line to php.ini
## cgi.fix_pathinfo = 1
## if it still doesn't work, rename php.ini to php5.ini
############################################
## this line is specific for 1and1 hosting
#AddType x-mapp-php5 .php
#AddHandler x-mapp-php5 .php
############################################
## default index file
DirectoryIndex index.php
<IfModule mod_php5.c>
############################################
## adjust memory limit
# php_value memory_limit 64M
php_value memory_limit 256M
php_value max_execution_time 18000
############################################
## disable magic quotes for php request vars
php_flag magic_quotes_gpc off
############################################
## disable automatic session start
## before autoload was initialized
php_flag session.auto_start off
############################################
## enable resulting html compression
#php_flag zlib.output_compression on
###########################################
# disable user agent verification to not break multiple image upload
php_flag suhosin.session.cryptua off
###########################################
# turn off compatibility with PHP4 when dealing with objects
php_flag zend.ze1_compatibility_mode Off
</IfModule>
<IfModule mod_security.c>
###########################################
# disable POST processing to not break multiple image upload
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>
<IfModule mod_deflate.c>
############################################
## enable apache served files compression
## http://developer.yahoo.com/performance/rules.html#gzip
# Insert filter on all content
###SetOutputFilter DEFLATE
# Insert filter on selected content types only
#AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript
# Netscape 4.x has some problems...
#BrowserMatch ^Mozilla/4 gzip-only-text/html
# Netscape 4.06-4.08 have some more problems
#BrowserMatch ^Mozilla/4\.0[678] no-gzip
# MSIE masquerades as Netscape, but it is fine
#BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
# Don't compress images
#SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
# Make sure proxies don't deliver the wrong content
#Header append Vary User-Agent env=!dont-vary
</IfModule>
<IfModule mod_ssl.c>
############################################
## make HTTPS env vars available for CGI mode
SSLOptions StdEnvVars
</IfModule>
<IfModule mod_rewrite.c>
############################################
## enable rewrites
Options +FollowSymLinks
RewriteEngine on
############################################
## you can put here your magento root folder
## path relative to web root
#RewriteBase /
############################################
## workaround for HTTP authorization
## in CGI environment
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
############################################
## always send 404 on missing files in these folders
RewriteCond %{REQUEST_URI} !^/(media|skin|js)/
############################################
## never rewrite for existing files, directories and links
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
############################################
## rewrite everything else to index.php
RewriteRule .* index.php [L]
</IfModule>
############################################
## Prevent character encoding issues from server overrides
## If you still have problems, use the second line instead
AddDefaultCharset Off
#AddDefaultCharset UTF-8
<IfModule mod_expires.c>
############################################
## Add default Expires header
## http://developer.yahoo.com/performance/rules.html#expires
ExpiresDefault "access plus 1 year"
</IfModule>
############################################
## By default allow all access
Order allow,deny
Allow from all
###########################################
## Deny access to release notes to prevent disclosure of the installed Magento version
<Files RELEASE_NOTES.txt>
order allow,deny
deny from all
</Files>
############################################
## If running in cluster environment, uncomment this
## http://developer.yahoo.com/performance/rules.html#etags
#FileETag none
Please give me an instruction on how to deal with this error.
On my side it was not a permission problem but simply (and the same is in your .htaccess) the line with:
RewriteBase /
was commented.
Uncommenting it solved the problem.
Set permission 755 to necessary files and folders
You've hit a rock on this one. The permissions have been changed on items that need other permissions than 755 set.
Resetting File Permissions
The base things to watch out for are the files & directories that must be writeable:
- file: magento/var/.htaccess
- directory: magento/app/etc
- directory: magento/var
- all the directories under: magento/media
chmod o+w var var/.htaccess app/etc
chmod -R o+w media
I had this same problem.
The directory for my Magento website on my Ubuntu server is: /var/www/magento
When running Magento initial installation I selected "No" for Use Web Server Rewrites. This setting is under Admin Panel - System - General - Web.
In .htaccess of root magento folder after finishing the initial installation it had:
RewriteBase /magento/
As noted before my folder was /var/www/magento/
I changed Web Server Rewrites to Yes. In .htaccess I changed:
RewriteBase /
Works fine now.
I ran into this issue aswell
adding
RewriteBase /
to the .htaccess brought me a step further.
After this I ran into the next issue:
Could not determine temp directory, please specify a cache_dir manually";i:1;s:4307:"#0 /XXX/XXX/lib/Zend/Cache/Backend.php(217): Zend_Cache::throwException('Could not deter...')
Solution for this was to edit the
\lib\Zend\Cache\Backend\File.php
In the file.php search for
'cache_dir' => null,
and replace with
'cache_dir' => "var/tmp/",
I hope this saves somebody else some time.

Apache + Mongrel Cluster = Wrong server config!

I'm trying to get Ruby on Rails going on a Windows 2003 Server. I've installed the Mongrel service and Apache (and RoR, etc).
When I serve an app using just Mongrel, everything comes up perfectly.
So, now I am down to the Apache configuration... Apparently I can't seem to get that right. When I visit my pages, I am returned the correct HTML, but it's returned with the Content-Type set to text/plain instead of html or xhtml... In addition, If I try to get to one of the css pages, I get a 500 Internal Server error (served back as HTML, returned with the text/plain Content-Type).
Here is my Virtual Host file (Any help would be VERY VERY VERY appreciated!):
NameVirtualHost *:8080
#Proxy balancer section (create one for each ruby app cluster)
<Proxy balancer://myapp_cluster>
Order allow,deny
Allow from all
BalancerMember http://rails.localdomain.com:3010
#BalancerMember http://myapp:3011
</Proxy>
#Virtual host section (create one for each ruby app you need to publish)
<VirtualHost *:8080>
ServerName rails.localdomain.com
DocumentRoot c:/www/app/public/
<Directory c:/www/app/public/ >
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
ProxyRequests Off
ProxyPass / balancer://myapp_cluster
ProxyPassReverse / balancer://myapp_cluster
ProxyPreserveHost On
#SetOutputFilter INFLATE;DEFLATE
#SetOutputFilter proxy-html
#log files
ErrorLog c:/www/log/app_error.log
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
CustomLog c:/www/log/app_access.log combined
#Rewrite stuff
RewriteEngine On
# Check for maintenance file and redirect all requests
RewriteCond %{DOCUMENT_ROOT}/system/maintenance.html -f
RewriteCond %{SCRIPT_FILENAME} !maintenance.html
RewriteRule ^.*$ /system/maintenance.html [L]
# Rewrite index to check for static
RewriteRule ^/$ /index.html [QSA]
# Rewrite to check for Rails cached page
RewriteRule ^([^.]+)$ $1.html [QSA]
# Redirect all non-static requests to cluster
RewriteCond %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
RewriteRule ^/(.*)$ balancer://myapp_cluster%{REQUEST_URI} [P,QSA,L]
# Deflate
#AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml application/xhtml+xml text/javascript text/css
#BrowserMatch ^Mozilla/4 gzip-only-text/html
#BrowserMatch ^Mozilla/4\.0[678] no-gzip
#BrowserMatch \\bMSIE !no-gzip !gzip-only-text/html
</VirtualHost>
OK, here's part of the answer. This part deals with the .css and .js files. Apparently it relates to trailing slashes... I had to remove some slashes and add some others...
Removed:
DocumentRoot c:/www/app/public
<Directory c:/www/app/public >
Added:
ProxyPass / balancer://myapp_cluster/
ProxyPassReverse / balancer://myapp_cluster/
Now I can pull up the .css and .js files just fine...
HOWEVER: I am still having the issue of Apache NOT sending the right headers. Right inside the HTML that I'm returning I have this:
But it's STILL returning text/plain (the DefaultType as set in the httpd.conf).
PLEASE, if anyone has any ideas, let me know!!!!!
Thanks
I heavily recommend a linux host for RoR. Unicorn and Passenger are way better tools than mongrel clusters. See github blog post about it.

Resources