Posted by Dhaval Parikh on Jun 27, 2011
Guys,
I was given a task to setup https using self signed certificate using nginx in our latest rails app. This was basically for the paypal page where we were accepting credit card details on our site.
Below is the nginx.conf file configuration which u require in order to implement SSL certificate. If you see closely there are 2 port defined. 1) port 80 2) port 443. Port 80 is for standard http request and port 443 is for https request.
#————————code starts below————————————-
#user nobody;
worker_processes 4;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main ‘$remote_addr – $remote_user [$time_local] ‘
‘”$request” $status $body_bytes_sent “$http_referer” ‘
‘”$http_user_agent” “$http_x_forwarded_for”‘;
sendfile on;
tcp_nopush on;
tcp_nodelay off;
#keepalive_timeout 0;
keepalive_timeout 65;
gzip on;
gzip_http_version 1.0;
gzip_comp_level 2;
gzip_buffers 16 8k;
gzip_types text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript ;
upstream main{
server 127.0.0.1:8000;
server 127.0.0.1:8001;
server 127.0.0.1:8002;
server 127.0.0.1:8003;
}
server {
listen 80;
#server_name yourdomain.com;
#client_max_body_size 4M;
client_body_buffer_size 128k;
root /var/www/yourapplication/public/;
# needed to forward user.s IP address to rails
proxy_set_header X-Real-IP $remote_addr;
# needed for HTTPS
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect false;
proxy_max_temp_file_size 0;
location ~ ^/(images|javascripts|stylesheets|product)/ {
expires 10y;
}
# If the file exists as a static file serve it directly without
# running all the other rewite tests on it
if (-f $request_filename) {
break;
}
# check for index.html for directory index
# if its there on the filesystem then rewite
# the url to add /index.html to the end of it
# and then break to send it to the next config rules.
if (-f $request_filename/index.html) {
rewrite (.*) $1/index.html break;
}
# redirect the traffic to the upstream mongrel defined as .main.
proxy_pass http://main/;
}
}
#———————–https————
server {
listen 443;
server_name yourdomain.com;
ssl on;
ssl_certificate /etc/ssl/certs/myssl.crt;
ssl_certificate_key /etc/ssl/private/myssl.key;
#client_max_body_size 4M;
client_body_buffer_size 128k;
root /var/www/yourapplication/public/;
# needed to forward user.s IP address to rails
proxy_set_header X-Real-IP $remote_addr;
# needed for HTTPS
proxy_set_header X_FORWARDED_PROTO https;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-Url-Scheme $scheme;
proxy_redirect off;
proxy_max_temp_file_size 0;
location ~ ^/(images|javascripts|stylesheets|product)/ {
expires 10y;
}
# If the file exists as a static file serve it directly without
# running all the other rewite tests on it
if (-f $request_filename) {
break;
}
# check for index.html for directory index
# if its there on the filesystem then rewite
# the url to add /index.html to the end of it
# and then break to send it to the next config rules.
if (-f $request_filename/index.html) {
rewrite (.*) $1/index.html break;
}
# redirect the traffic to the upstream mongrel defined as .main.
proxy_pass http://main/;
}
}
#—————————-https———————–
In the code above the most important part is
ssl on;
ssl_certificate /etc/ssl/certs/myssl.crt;
ssl_certificate_key /etc/ssl/private/myssl.key;
Now how to generate self signed certificates i will let u know in my next post. (Though i should have covered it b4 but ne ways will do it now)
Thats all. You can add and remove basic paraments you want from the above given nginx.conf file.
Let me know if you find any issues in implementing SSL for your app.
Tags: rails + ssl, rails + ssl + nginx, ssl + nginx
Posted by Dhaval Parikh on May 19, 2011
Guys if you get this error you are being redirected while working with rails 2.3.7 + nginx + mongrel
in production mode. Just add the code below in the initializer folder in a file called mongrel.rb
if Rails.version == ’2.3.8′ && Gem.available?(‘mongrel’, Gem::Requirement.new(‘~>1.1.5′))
&& self.class.const_defined?(:Mongrel)
# Pulled right from latest rack. Old looked like this in 1.1.0 version.
#
# def [](k)
# super(@names[k] ||= @names[k.downcase])
# end
#
module Rack
module Utils
class HeaderHash < Hash
def [](k)
super(@names[k]) if @names[k]
super(@names[k.downcase])
end
end
end
end
# Code pulled from the ticket above.
#
class Mongrel::CGIWrapper
def header_with_rails_fix(options = ‘text/html’)
@head['cookie'] = options.delete(‘cookie’).flatten.map { |v| v.sub(/^\n/,”) } if options.class != String and options['cookie']
header_without_rails_fix(options)
end
alias_method_chain :header, :rails_fix
end
# Pulled right from 2.3.8 ActionPack. Simple diff was
#
# if headers.include?(‘Set-Cookie’)
# headers['cookie'] = headers.delete(‘Set-Cookie’).split(“\n”)
# end
#
# to
#
# if headers['Set-Cookie']
# headers['cookie'] = headers.delete(‘Set-Cookie’).split(“\n”)
# end
#
module ActionController
class CGIHandler
def self.dispatch_cgi(app, cgi, out = $stdout)
env = cgi.__send__(:env_table)
env.delete “HTTP_CONTENT_LENGTH”
cgi.stdinput.extend ProperStream
env["SCRIPT_NAME"] = “” if env["SCRIPT_NAME"] == “/”
env.update({
“rack.version” => [0,1],
“rack.input” => cgi.stdinput,
“rack.errors” => $stderr,
“rack.multithread” => false,
“rack.multiprocess” => true,
“rack.run_once” => false,
“rack.url_scheme” => ["yes", "on", "1"].include?(env["HTTPS"]) ? “https” : “http”
})
env["QUERY_STRING"] ||= “”
env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"]
env["REQUEST_PATH"] ||= “/”
env.delete “PATH_INFO” if env["PATH_INFO"] == “”
status, headers, body = app.call(env)
begin
out.binmode if out.respond_to?(:binmode)
out.sync = false if out.respond_to?(:sync=)
headers['Status'] = status.to_s
if headers['Set-Cookie']
headers['cookie'] = headers.delete(‘Set-Cookie’).split(“\n”)
end
out.write(cgi.header(headers))
body.each { |part|
out.write part
out.flush if out.respond_to?(:flush)
}
ensure
body.close if body.respond_to?(:close)
end
end
end
end
end
Thats all just restart your server nginx and mongrel cluster and the error should be gone.
Tags: redirected + rails 2.3.8, redirected error + nginx, redirected error + rails 2.3.8
Posted by Dhaval Parikh on Jan 20, 2011
Hello guys
Posting after a long time. But any ways below are the steps if you want to deploy a rails app on ec2 directly without using any 3rd party service providers
All the details mentioned below after for ubuntu so path might vary for other Linux flavours.
step 1 = Set java home. Ofcourse you need to have java installed and I assume that you already have it installed.
JAVA_HOME=/usr/lib/jvm/java-6-openjdk/
export JAVA_HOME
PATH=$PATH:$JAVA_HOME/bin
export PATH
Step 2 = login to amazon aws go to the account tab and download security credentials. You will see 2 things
1) private key 2) certificate
Download them and store it on some path like /home/dhaval/cert or whatevery
Than export the keys and set it up with the following commands
export EC2_PRIVATE_KEY=/home/dhaval/cert/pk-2spdXHCQ4HDMJNCULJB5NA4JNLE7SWOR.pem
export EC2_CERT=/home/dhaval/cert/cert-2spdJXHCQ4HDMJNCULJB5NA4JNLE7SWOR.pem
Step 3 = Download api tools available on aws site
http://aws.amazon.com/developertools/351?_encoding=UTF8&jiveRedirect=1
export it and set the path
export EC2_HOME=/home/dhaval/cert/ec2-api-tools-1.3-62308
export PATH=$EC2_HOME/bin:$PATH
Step 4 = set up ssh keys using the following commands
ec2-add-keypair gsg-keypair
Now save this generated kaypair in ~/.shh folder with name id_rsa-gsg-keypair
Step 5 = Start an instance using the command below
ec2-run-instances (ami instance name) -k gsg-keypair
Step 6 = Check status of the instance
check status with
ec2-describe-instances (instant name)
eg.
ec2-describe-instances i-10a64379
Step 7 = Authorization of network ports using commands as below
ec2-authorize default -p 22
ec2-authorize default -p 80
Step 8 = Connect to your instance using the command below
ssh -i id_rsa-gsg-keypair root@machine_name
Thats all once these steps are done you can see the instance running on the aws console.
Than install ruby gems + rails + other required gems and packages and you are set to go.
In order to upload your files you can use Capistrano or also you can ssh through ftp using the key specified.
Hope this helps. If you are stuck at any step do feel free to ask question and I shall get back to you.
Njoi
Tags: amazon + rails app, ec2 + rails, rails amazon
Posted by Dhaval Parikh on Sep 18, 2010
Today we were trying to move one project of rails from one pc to the other. We took the source code along with the db (since the db had data in it and it was required) and configured it. But when we started the server using ruby script/server we got a strange error missing rsruby
searched for it and tried few things. Finally got it solved in 3 steps
>export R_HOME=/usr/lib/R
> sudo ln -s /usr/lib/R/lib/libR.so /usr/lib/libR.so
> gem install rsruby — –with-R-dir=$R_HOME –with-R-include=/usr/share/R/include/
Thats all… rsruby will be installed on your system and the project will be running without any issue.
Hope this works for you
Thanks
Tags: missing rsruby, rsruby error, solve missing rs-ruby error
Posted by Dhaval Parikh on Jun 23, 2010
Are you getting cookie overflow error when you are loading a lot of flash[:notices] ??
Something like CGI::Session::CookieStore::CookieOverflow
if so here is a solution for it
Just write this method in ur controller
before_filter :session_cleanup
def session_cleanup
backup = session.data.clone
reset_session
backup.each { |k, v| session[k] = v unless k.is_a?(String) && k
=~ /^as:/ }
end
What this will do is it will clear old data thats already there in the session and restore this one.
The above method wont work if your data size is >= 4k in that case the only solution is to use another session store.
Hope this helps
… Njoi
Tags: cookie overflow, flash notice overflow error, handle cookie over flow + rails
Posted by Dhaval Parikh on Jun 16, 2010
Here is a small post on how to read an xml file using Hpricot in your Rails application.
First of all you need to install hpricot with the following command
gem install hpricot
Here is a sample xml file which I want to read. You can just paste the following code and create .xml file
<profiles>
<profile>
<name> test </name>
<user_ids>
<user_id>39</user_id>
</user_ids>
</profile>
<profile>
<name> test 123</name>
<user_ids>
<user_id>39</user_id>
<user_id>46</user_id>
</user_ids>
</profile>
</profiles>
Now here comes the code to read this file. Don’t forget to add require ‘hpricot’ in the controller where you are putting this code.
test = Hpricot::XML(File.open(“test.xml”, “r”))
(test/:profile).each do |pro| render :text=>(((pro.at(“name”).innerHTML.strip).to_s)+”=>”+(pro.at(“ _id”).innerHTML.strip).to_s).inspect and return false
end
Remove .inspect and return false once u get the required output
Hope this helps. If you have any doubts just post a message and I will try to reply.
Tags: hpricot + rails, read xml + rails, xml + hpricot + rails